#-*- coding:utf-8 -*-
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def FindKthToTail(self, head, k):
#定义两个变量,中间间隔为k直到为空
firstpoint = head
secondpoint = head
for i in range(k):
secondpoint = secondpoint.next
while secondpoint:
firstpoint = firstpoint.next
secondpoint = secondpoint.next
return firstpoint.val
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,2))
剑指————输出链表倒数第k个值
最新推荐文章于 2024-07-22 22:58:19 发布