题解 | #从单向链表中删除指定值的节点#
从单向链表中删除指定值的节点
https://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f
import enum
import sys
class Node(object):
def __init__(self, val=0):
self.val = val
self.next = None
for line in sys.stdin:
arr = list(map(int, line.strip().split(' ')))
n = arr[0]
v = arr[-1]
# 构造链表
head = Node(0)
p = head
q = Node(arr[1])
p.next = q
p = q
for i in range(2, len(arr)-2, 2):
q = Node(arr[i])
p = head.next
# print(arr[i])
while p.val != arr[i+1]:
p = p.next
t = p.next
p.next = q
q.next = t
# 删除结点
p = head
q = head.next
while q.val != v:
p = p.next
q = q.next
p.next = q.next
# 打印输出
res = []
p = head.next
while p:
res.append(p.val)
p = p.next
print(' '.join(list(map(str, res))))

查看1道真题和解析