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

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

https://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f

class Link:
    def __init__(self, head) -> None:
        self.head = head
        self.next = None

    def insert(self, tar, val):
        l = Link(val)

        if self.head == tar:
            self.next, l.next = l, self.next
            return

        cur = self.next

        while cur:
            if cur.head == tar:
                cur.next, l.next = l, cur.next
                break
            cur = cur.next

    def delete(self, val):
        if self.head == val:
            return self.next

        cur, pre = self.next, self
        while cur:
            if cur.head == val:
                pre.next = cur.next
                return self
            cur, pre = cur.next, cur

nodes = input().strip().split()[1:]

l = Link(nodes[0])

for i in range(1, len(nodes)-1, 2):
    l.insert(nodes[i + 1], nodes[i])

l = l.delete(nodes[-1])

print(l.head, end=' ')
cur = l.next
while cur:
    print(cur.head, end=' ')
    cur = cur.next

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务