题解 | #【模板】链表#
【模板】链表
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