I am creating linked list. In my linked list i have str method in both classes Node and LinkedList. What i was trying to do is, print object in readable format whenever i print object to console. So i used str method in Node class, but i have no idea how this is printing all elements in the linked list without any loop whenever i use print() function.
class LinkedList:
def __init__(self):
self.head = None
def __str__(self):
if self.head is not None:
return str(self.head)
return 'empty linked list'
def insert(self, data):
if self.head is None:
self.head = Node(data)
else:
head = self.head
while head.next is not None:
head = head.next
head.next = Node(data)
class Node:
def __init__(self, data):
self.data = data
self.next = None
def __str__(self):
return f"{self.data}\n{self.next}"
elems1 = [1,2,3,4]
llist1 = LinkedList()
for elem in elems1:
llist1.insert(elem)
print(llist1)
I figured out that using {self.next} in str method in Node class is causing such behaviour but i have now idea how this is working.
Lets go down (or up if you prefer) the call stack.
print(llist1)
this calls the method LinkedList.__str__
LinkedList.__str__
then calls str(self.head)
which then calls the method Node.__str__
Node.__str__
then returns the expression f"{self.data}\n{self.next}"
self.next
in that f-string calls the __str__
method)Node.__str__
on self.next
which as we know will then call its self.next
and so on and so on until self.next == None
in which case there's no more __str__
method to callself.next
will return the empty string and stop the recursive call stackYou've created a recursive program without realizing it.