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

import sys
# example input: 5 2 3 2 4 3 5 2 1 4 3

class Node:
    
    def __init__(self, val):
        self.val = val
        self.next = None
    
    def __repr__(self):
        return f'Node ({self.val})'
    

class LinkedList:
    
    def __init__(self, head):
        self.head = Node(-1)
        self.head.next = Node(head)
    
    def insert(self, new_node, value):
        curr = self.head
        # print(value, new_node)
        while curr and curr.val != value:
            # print(curr)
            curr = curr.next
        tmp = curr.next
        curr.next = new_node
        new_node.next = tmp
    
    def delete(self, value):
        curr = self.head
        while curr.next and curr.next.val != value:
            # print(curr.next)
            curr = curr.next
        curr.next = curr.next.next
        
    def get_values(self):
        curr = self.head
        res = []
        while curr:
            res.append(curr.val)
            curr = curr.next
        return res[1:]
        
   
raw_input = []
for i,line in enumerate(sys.stdin):
    raw_input.append(line.strip())
    if i == 1:
        break

input_nums = [int(i) for i in raw_input[0].split(' ')]
n = input_nums[0]
head_value = input_nums[1]
insert_cmds = input_nums[2:2*n]
rm_value = input_nums[2*n]
linked_list = LinkedList(head_value)
for i in range(0, len(insert_cmds), 2):
    new_value, exist_value = insert_cmds[i], insert_cmds[i+1]
    linked_list.insert(Node(new_value), exist_value)
linked_list.delete(rm_value)
res = linked_list.get_values()
print(' '.join([str(i) for i in res]))


全部评论

相关推荐

2024-12-13 11:44
门头沟学院 后端
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务