题解 | #【模板】链表#

【模板】链表

https://www.nowcoder.com/practice/97dc1ac2311046618fd19960041e3c6f

class Node:
    def __init__(self, val, next=None) -> None:
        self.val = val
        self.next = next

class LinkedList:
    def __init__(self) -> None:
        self.head = Node(-1)
        self.size = 0

    def insert(self, x, y):
        pre = self.head
        cur = pre.next
        while cur and cur.val!=x:
            pre = pre.next
            cur = cur.next
        pre.next = Node(y)
        pre.next.next = cur
        self.size += 1

    def delete(self, x):
        pre = self.head
        cur = pre.next
        while cur and cur.val!=x:
            pre = pre.next
            cur = cur.next
        if not cur:
            return
        pre.next = cur.next
        self.size -= 1

    def print(self):
        if self.size == 0:
            print('NULL')
            return
        cur = self.head.next
        while cur:
            print(cur.val, end=' ')
            cur = cur.next


while True:
    try:
        n = int(input())
        lst = LinkedList()
        for i in range(n):
            line = input().split()
            if line[0] == 'insert':
                lst.insert(int(line[1]), int(line[2]))
            elif line[0] == 'delete':
                lst.delete(int(line[1]))
        lst.print()
    except:
        break

全部评论

相关推荐

不愿透露姓名的神秘牛友
09-30 19:49
牛客798932866号:已经出薪资了嘛
投递汇川技术等公司10个岗位
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务