无法附加到 python 中的链表

Unable to append to a linked list in python

我正在尝试学习如何创建链表。这是我第一次这样做,代码失败的原因可能是我缺少的基本内容。

也就是说,即使在使用 vs code 的调试器之后我也无法弄清楚。第二次调用时,它只是停在append方法的末尾。

我正在使用递归遍历到尾部。这会是问题所在吗?

class Node:

    def __init__(self, data, next_node=None):
        self.data = data
        self.next = next_node


class LinkedList:

    def __init__(self):
        self.head = None

    def __repr__(self):

        if not self.head:
            return 'Linked list is empty'

        linked_list = self.head.data

        if self.head.next == None:
            return linked_list

        current = self.head

        while current.next != None:
            linked_list += '\n|\nV' + current.data

        return linked_list

    def append(self, value):

        if not self.head:
            self.head = Node(data=value)
            return

        tail = self.tail()

        tail.next = Node(data=value)

    def tail(self):

        tail = self._traverse_to_tail(self.head)

        while tail.next != None:
            tail = self._traverse_to_tail(tail)

        return tail

    def _traverse_to_tail(self, current_node, recursion_count=0):
        print(current_node.data)
        if recursion_count > 997:
            return current_node

        if current_node.next == None:
            return current_node

        current_node = current_node.next
        recursion_count += 1

        return self._traverse_to_tail(current_node, recursion_count)


if __name__ == '__main__':
    ll = LinkedList()

    ll.append('foo')
    ll.append('baz')

    print(ll)

问题是您在 __repr__() 函数中有一个无限循环,因为您从不递增 current

    def __repr__(self):

        if not self.head:
            return 'Linked list is empty'

        linked_list = self.head.data

        if self.head.next == None:
            return linked_list

        current = self.head

        while current.next != None:
            current = current.next
            linked_list += '\n|\nV' + current.data

        return linked_list