繁体   English   中英

在末尾插入元素时单链表无限循环 python

[英]singly linked list infinite loop when inserting an element at the end python

当我想在我的链表末尾添加一个元素时,它会导致无限循环,这是我使用的方法

#insert at the end of the list

def append(self, data=None):
    new_node = Node(data)
    if self.head is None:
        self.head = new_node
    itr = self.head
    while itr.next:
        itr.next = new_node
        itr = itr.next

如果列表为空,则在头部添加新节点后,您的代码应返回。

之后你的while循环是一个无限循环

您需要在添加之前更新它的 position 然后在循环外添加到它

def append(self, data=None):
    new_node = Node(data)
    if self.head is None:
        self.head = new_node
        return
    itr = self.head
    while itr.next:
        itr = itr.next
    itr.next = new_node

你的 Node() 也应该有一个参数 next

你的问题在循环中:

while itr.next:
   itr.next = new_node
   itr = itr.next

将项目附加到空列表时, new_node itr 您将itr.next设置为new_node ,所以现在new_node.next等于new_node 您现在已经在列表中创建了一个循环,因此它将永远循环。

将项目附加到列表时,您应该只修改最后一个元素 - 循环仅用于遍历列表以到达末尾。 它应该看起来像:

def append(self, data=None):
    new_node = Node(data)
    if self.head is None:
        self.head = new_node
    else: 
        # you only need to traverse the list when it isn't empty
        itr = self.head
        while itr.next:
            itr = itr.next
        itr.next = new_node # only add the new node after traversing the list

话虽如此,这种追加方法是O(n)复杂度,您可以通过保留指向列表尾部的指针并修改尾部而不遍历列表来找到它,从而使其成为O(1)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM