超时求助 | #【模板】链表#

运行超时
运行超时:您的程序未能在规定时间内运行结束,请检查是否循环有错或算法复杂度过大。
8/10 组用例通过
运行时间2001ms
占用内存6696KB
用例输入:10000 insert 0 1607569717 insert 0 740786429 insert 0 463882232 insert 0 384203712······························

  1. 用链表的方式去做,发现数据【10000】时,超时时···
  2. 想了一个下午,换来超时,心态崩了···
  3. 有没有大佬能帮忙改进下超时的代码···感激不尽" src="https://uploadfiles.nowcoder.com/images/20220815/318889480_1660553763930/8B36D115CE5468E380708713273FEF43" />
class ListNode:
    def __init__(self,x=0):
        self.val = x
        self.next = None
        
def insertNode(root,root2,x,y):
    node = ListNode(y)
    if not root2:
        root.next = node
        return 
    
    while root2:
        if root2.val == x:
            node.next = root2 
            root.next = node
            return 
        root = root.next
        root2 = root2.next
        
    root.next = node

def deletNode(root,root2,x): 
    while root2:
        if root2.val == x:
            root.next = root2.next
            return
        else:
            root = root.next
            root2 = root2.next   

n = int(input())
xu = ListNode(-1)
# root = None
# root2 = None
while n > 0:
    root = xu
    root2 = xu.next
    m = input().split()
    if m[0] == 'insert':
        insertNode(root,root2,int(m[1]),int(m[2]))
    elif m[0] == 'delete':
        deletNode(root,root2,int(m[1]))
    n = n - 1
        
root = xu
while root.next:
    print(root.next.val,end=' ')
    root = root.next
root = xu
if not root.next:
    print('NULL')

    


全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务