题解 | 从单向链表中删除指定值的节点
从单向链表中删除指定值的节点
https://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f
import sys
class ListNode:
def __init__(self, value=0, next=None):
self.value = value
self.next = next
def construct_linked_list(n, head_value, pairs):
# 创建头节点
head = ListNode(head_value)
current = head
value_to_node = {head_value: head}
# 根据二元组插入节点
for a, b in pairs:
new_node = ListNode(a)
value_to_node[a] = new_node
if b in value_to_node:
node_b = value_to_node[b]
new_node.next = node_b.next
node_b.next = new_node
return head
def delete_node(head, k):
dummy = ListNode(0)
dummy.next = head
prev = dummy
current = head
while current:
if current.value == k:
prev.next = current.next
else:
prev = current
current = current.next
return dummy.next
def print_linked_list(head):
current = head
values = []
while current:
values.append(current.value)
current = current.next
print(" ".join(map(str, values)))
data=list(map(int,sys.stdin.readline().strip().split()))
n = data[0]
head_value = data[1]
pairs = [(data[2*i+2],data[2*i+3]) for i in range(n-1)]
k = data[-1]
# 构造链表
head = construct_linked_list(n, head_value, pairs)
# 删除值为 k 的节点
head = delete_node(head, k)
# 输出剩余的链表
print_linked_list(head)
查看1道真题和解析
