题解 | #【模板】链表#
【模板】链表
https://www.nowcoder.com/practice/97dc1ac2311046618fd19960041e3c6f
import sys class Node: def __init__(self,val): self.val=val self.next=None class Linklist: def __init__(self,val,head): self.val=val self.next=None self.head = head def insert(self,x,y): cur = head node = Node(y) if not cur.next: node.next=cur.next cur.next=node return while cur.next: if cur.next.val == x: node.next=cur.next cur.next=node return cur=cur.next node.next=cur.next cur.next=node return def delete(self,x): cur = head while cur.next: if cur.next.val==x: cur.next=cur.next.next return cur=cur.next def traversal(self): L=[] cur =head.next if not cur: print ("NULL") while cur: L.append(cur.val) cur=cur.next L = list(map(str,L)) #for x in L: print(" ".join(L)) n = int(input()) i=1 operations=[] while i<=n: operations.append(input()) i+=1 head =Node(-1) link=Linklist(-1,head) for x in operations: x=x.split() #tmp =x[:6] if x[0]=="insert": m=int(x[1]) n=int(x[2]) link.insert(m,n) elif x[0] =="delete": #n=x[7] n=int(x[1]) link.delete(n) link.traversal()