Home > Back-end >  Unable to append to a linked list in python
Unable to append to a linked list in python

Time:09-29

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. It simply stops at the end of the append method when it is called the second time.

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)

CodePudding user response:

The problem is you have an infinite loop in the __repr__() function, because you never increment 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
  • Related