简体   繁体   English

无法append到python中的链表

[英]Unable to append to a linked list in python

I'm trying to learn how to create linked lists.我正在尝试学习如何创建链表。 This is my first time doing this and the reason of code failure may be something basic I'm missing.这是我第一次这样做,代码失败的原因可能是我缺少的基本内容。

That being said, I am unable to figure out even after using vs code's debugger.话虽如此,即使在使用 vs code 的调试器之后我也无法弄清楚。 It simply stops at the end of the append method when it is called the second time.第二次调用时,它只是停在 append 方法的末尾。

I am using recursion to traverse to the tail.我正在使用递归遍历到尾部。 Could that be a the problem?这可能是个问题吗?

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)

The problem is you have an infinite loop in the __repr__() function, because you never increment current .问题是你在__repr__() function 中有一个无限循环,因为你从不增加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

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

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