题目描述
解题思路
使用双指针,指针1先走k步,然后两个指针同时往后移动,指针1到达表尾时,指针2位倒数第k个结点。
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def FindKthToTail(self, head, k):
# write code here
if not head or k < 1:
return None
p1 = head
p2 = head
while k > 0:
if not p1:
return None
p1 = p1.next
k -= 1
while p1:
p2 = p2.next
p1 = p1.next
return p2