题解 | #链表中倒数最后k个结点#
链表中倒数最后k个结点
https://www.nowcoder.com/practice/886370fe658f41b498d40fb34ae76ff9
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
# @param pHead ListNode类
# @param k int整型
# @return ListNode类
#
# 双指针法,先将右指针移动 k-1 步,然后再同时移动左指针和右指针,当右指针移动到最后一个节点时,输出左指针
class Solution:
def FindKthToTail(self , pHead: ListNode, k: int) -> ListNode:
if pHead == None:
return None
if k <= 0:
return None
l, r = pHead, pHead
for i in range(k-1):
r = r.next
if r == None:
return None
while r.next != None:
l = l.next
r = r.next
return l
