JZ14 链表中倒数最后k个结点
my version
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def FindKthToTail(self , pHead , k ):
# write code here
length = 0
p = pHead
while p:
length += 1
p = p.next
if k > length:
return
p = pHead
while length > k:
length -= 1
p = p.next
return p
book method
只遍历1遍,用两个指针
class Solution:
def FindKthToTail(self , pHead , k ):
if pHead:
p1 = pHead
p2 = pHead
while p1 and k>0:
p1 = p1.next
k -= 1
if k == 0:
while p1:
p1 = p1.next
p2 = p2.next
return p2
return None
注意边界条件