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)
self._traverse_to_tail()finds the last node, why do you need thewhileloop after calling that?whileloop just like the one you have inappend().self._traverse_to_tail()would raise a 'RecursionError'. I did not want to change the recursion limit so thewhileloop ensures I am at the last node regardless of the length of linked list.whileloop in__repr()__never updatescurrent, so it's an infinite loop.