题解 | #【模板】链表#

【模板】链表

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

全部评论

相关推荐

找不到工作死了算了:没事的,雨英,hr肯主动告知结果已经超越大部分hr了
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务