题解 | #【模板】链表#

【模板】链表

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()

全部评论

相关推荐

04-09 09:47
门头沟学院 Java
Arbelite_:2-3k,这工资还不如去摇奶茶
点赞 评论 收藏
分享
Z_eus:别打招呼直接发你的优势
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务