劍指offer14.連結串列中倒數第k個結點
阿新 • • 發佈:2019-01-05
題目描述
輸入一個連結串列,輸出該連結串列中倒數第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 slow, fast = head, head for i in range(k): if fast == None: return None fast = fast.next while fast: fast = fast.next slow = slow.next return slow