题目描述
输入一个链表,输出该链表中倒数第k个结点。
class Solution:
def FindKthToTail(self, head, k):
# write code here
if k<=0 or head==None:
return None
p1=head
p2=head
while k>1:
if p2.next!=None:
p2=p2.next
k-=1
else:
return None
while p2.next!==None:
p1=p1.next
p2=p2.next
return p1
用两个指针代替一个指针的两次遍历。第一个指针先走k-1步,当第一个指针指向链尾时,第二个指针指向倒数第k个节点。