题解 | #输出单向链表中倒数第k个结点#
输出单向链表中倒数第k个结点
https://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d
# 创建链表节点类
class NodeList(object):
def __init__(self,value,next=None) -> None:
self.value = value
self.next = next
# 构建单向链表
def builtlinklist(nums):
if not nums:
return None
head = NodeList(nums[0])
current = head
for i in range(1,len(nums)):
current.next = NodeList(nums[i])
current = current.next
return head
# 利用快慢指针法寻找倒数K的节点
def getK(head,k):
fast = slow = head
for i in range(k):
fast = fast.next
while fast:
fast = fast.next
slow = slow.next
return slow
while True:
try:
n = int(input())
numbers = list(map(int,input().split()))
k = int(input())
head= builtlinklist(numbers)
result = getK(head,k)
print(result.value)
except:
break
#单向链表#