题目描述:
输入一个链表,输出该链表中倒数第k个结点。
解法
用快慢指针。fast和slow指针初始都指向链表头head。fast指针先走k步,slow指针再开始走。当fast指针指向None时,slow指针恰好指向链表倒数第k个结点。
代码:
class Solution:
def FindKthToTail(self, head, k):
fast, slow = head, head
for i in range(k):
if fast == None:
return None
fast = fast.next
while fast:
fast = fast.next
slow = slow.next
return slow