仿照一位c++大佬的答案,写了python的双指针
# 双指针
class ListNode(object):
def __init__(self, val=None, next=None):
self.val = val
self.next = next
def GetKthFromTail(head: ListNode, k):
p_fast, p_slow = head, head # init 快慢指针
for i in range(k):
if p_fast:
p_fast = p_fast.next
else: # 快指针先行k步, 如果不能到达k步, 则说明链表长度不够
return None
while p_fast: # 同步快慢指针, 快指针探底, 则慢指针抵达倒数第K个
p_fast = p_fast.next
p_slow = p_slow.next
return p_slow
if __name__ == "__main__":
while True:
try:
L, ls, k = int(input()), input().split(), int(input())
head = ListNode(ls[0])
cur = head
for i in range(1, L): # 输入链表
cur.next = ListNode(ls[i])
cur = cur.next
if k:
p_Kth = GetKthFromTail(head, k)
if p_Kth:
print(p_Kth.val)
else:
print('0')
else:
print('0')
except:
break