题解 | 输出单向链表中倒数第k个结点
输出单向链表中倒数第k个结点
https://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d
class ListNode():
def __init__(self,val=0):
self.val = val
self.next = None
def fun(num_list:list):
head = ListNode() #初始化一个虚拟头结点 val=0 next=None
current = head
for val in num_list:
current.next = ListNode(val)
current = current.next
fast = head.next
slow = head.next
for _ in range(k): #fast指针先往前遍历k步
if not fast:
print(None) #判断fast没有超出链表边界,如果超出边界,会返回head.next为None
break
fast = fast.next
else:
while fast:
slow = slow.next
fast = fast.next
print(slow.val)
while True:
try:
n = int(input())
num_list = list(map(int,input().split()))
k = int(input())
fun(num_list)
except Exception as error:
break
查看14道真题和解析