Python 鏈表中倒數第k個節點

輸入一個鏈表,輸出該鏈表中倒數第k個節點。

# -*- coding:utf-8 -*-
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None


class Solution:
    def FindKthToTail(self, head, k):
        firstPoint = head
        secondPoint = head
        for i in range(k):
            if firstPoint == None:
                return None
            firstPoint = firstPoint.next
        while firstPoint != None:
            firstPoint = firstPoint.next
            secondPoint = secondPoint.next
        return secondPoint


if __name__ == '__main__':
    l1 = ListNode(1)
    l2 = ListNode(2)
    l3 = ListNode(3)
    l4 = ListNode(4)
    l5 = ListNode(5)
    l1.next = l2
    l2.next = l3
    l3.next = l4
    l4.next = l5
    s = Solution()
    print(s.FindKthToTail(l1, 4).val)

運行結果爲:

2
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章