題目描述
知識點:鏈表
使用前後指針即可,前指針先走k-1步,然後兩個指針一起移動,當前指針指向最後一個節點,後指針正好指向倒數第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
quick_pointer = head
slow_pointer = head
ans = []
for i in range(k - 1):
if quick_pointer.next:
quick_pointer = quick_pointer.next
else:
return None
while quick_pointer.next:
quick_pointer = quick_pointer.next
slow_pointer = slow_pointer.next
return slow_pointer
拓展:若要求中間節點,可設置快慢指針,快指針一次走兩步,慢指針一次走一個,當快指針指向最後一個節點,慢指針指向中間節點。