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.
>Solution :
Lets go down (or up if you prefer) the call stack.
print(llist1)this calls the methodLinkedList.__str__- that
LinkedList.__str__then callsstr(self.head)which then calls the methodNode.__str__ - that
Node.__str__then returns the expressionf"{self.data}\n{self.next}" - in evaluating that expression, you then must call the self.next and then stringifyit. (putting that expression
self.nextin that f-string calls the__str__method) - so now you’ve called
Node.__str__onself.nextwhich as we know will then call itsself.nextand so on and so on untilself.next == Nonein which case there’s no more__str__method to call self.nextwill return the empty string and stop the recursive call stack
You’ve created a recursive program without realizing it.