题解 | 从单向链表中删除指定值的节点

从单向链表中删除指定值的节点

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)

全部评论

相关推荐

程序员花海:实习和校招简历正确格式应该是教育背景+实习+项目经历+个人评价 其中项目经历注意要体现业务 实习经历里面的业务更是要自圆其说 简历模板尽可能保持干净整洁 不要太花哨的
秋招吐槽大会
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务