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

Python 在末尾插入元素时的单链链表无限循环,python,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

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

#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循环就是一个无限循环

在添加到它之前,需要更新它的位置,然后在循环外部添加到它

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循环就是一个无限循环

在添加到它之前,需要更新它的位置,然后在循环外部添加到它

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
将项目追加到空列表时,
itr
is最初等于
new\u节点
。 您将
itr.next
设置为
new\u node
,因此现在
new\u node.next
等于
new\u 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)

您的问题在循环中:

while itr.next:
   itr.next = new_node
   itr = itr.next
将项目追加到空列表时,
itr
is最初等于
new\u节点
。 您将
itr.next
设置为
new\u node
,因此现在
new\u node.next
等于
new\u 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)
保留指向列表尾部的指针并修改尾部,而不遍历列表来找到它。

是否要添加单个元素或n个数字?请提供一个@matiss,OP正在尝试实现链接列表。@SırrıKırımlıoğlu我要添加n个元素您的循环正在将节点无限地添加到末尾并循环通过它们。你想添加一个元素还是n个数字?请提供一个@matiss。OP正在尝试实现一个链表。@SırrıKırımlıoğlu我想添加n个元素。你的循环正在将节点无限地添加到末尾并通过它们循环。非常感谢你的帮助,还有一个问题,如果列表为空,为什么我的代码在添加新节点后返回?为什么它什么也不返回呢?如果列表为空,那么添加节点就是函数的结尾。没有理由开始循环任何东西。您不返回任何内容,因为它不需要输出。这只是结束函数。如果没有返回,此代码将向空列表中添加两个节点。非常感谢您的帮助,还有一个问题:如果列表为空,为什么在添加新节点之后,我的代码应该返回?为什么它什么也不返回呢?如果列表为空,那么添加节点就是函数的结尾。没有理由开始循环任何东西。您不返回任何内容,因为它不需要输出。这只是结束函数。如果没有返回,此代码将向空列表中添加两个节点。