链表倒数第k个节点
1 # -*- coding:utf-8 -*- 2 # class ListNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.next = None 6 7 """双指针的关键是如何保持指针的距离为k-1""" 8 class Solution: 9 def FindKthToTail(self, head, k): 10 # write code here 11 if head == None or k==0: 12 return None 13 phead = head 14 pbehind = head 15 for i in range(k-1): #range的数字之差代表元素个数 16 if phead.next == None: 17 return None 18 else: 19 phead = phead.next 20 while phead.next != None: #倒数第二个节点依然满足,因此最终的phead是最后一个,最终的pbehind就是倒数第k个 21 phead = phead.next 22 pbehind = pbehind.next 23 return pbehind 24 25 26 """直接用列表实现""" 27 # -*- coding:utf-8 -*- 28 # class ListNode: 29 # def __init__(self, x): 30 # self.val = x 31 # self.next = None 32 33 class Solution: 34 def FindKthToTail(self, head, k): 35 # write code here 36 l = [] 37 while head: 38 l.append(head) 39 head = head.next 40 if len(l) < k or k < 1: 41 return None 42 return l[-k]