快慢指针思路
第一个指针走到K 然后第二个指针开始走
第一个指针走到尾巴的时候,第二个指针就是当前倒数K节点的指针
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def FindKthToTail(self, head, k):
# write code here
if head==None or k<0:
return None
# 快慢指针,第一个指针走k个以后,第二个走,如果第一个为None到头的时候,第二个就是倒数k
first = head
second = head
i = 0
while i < k:
if first != None:
first = first.next
i = i+1
else:
return None
while first != None:
first = first.next
second = second.next
return second