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

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]))


全部评论

相关推荐

程序员牛肉:主要是因为小厂的资金本来就很吃紧,所以更喜欢有实习经历的同学。来了就能上手。 而大厂因为钱多,实习生一天三四百的就不算事。所以愿意培养你,在面试的时候也就不在乎你有没有实习(除非是同级别大厂的实习。) 按照你的简历来看,同质化太严重了。项目也很烂大街。 要么换项目,要么考研。 你现在选择工作的话,前景不是很好了。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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