输入一个链表,输出该链表中倒数第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