1. 程式人生 > >劍指offer14.連結串列中倒數第k個結點

劍指offer14.連結串列中倒數第k個結點

https://www.nowcoder.com/practice/529d3ae5a407492994ad2a246518148a?tpId=13&tqId=11167&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

題目描述
輸入一個連結串列,輸出該連結串列中倒數第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