I’m trying to understand within my lesson how to read the below function called printBackward. How is it that when I type printBackward(node1) and my output is 3,2,1 which is what it’s suppose to do. I just don’t understand why that is. See below how I interpret it and please school me on where I saw it wrong…
class Node:
def __init__(self, cargo = None, next = None): # optional parameters. cargo and the link(next) are set to None.
self.cargo = cargo
self.next = next
def __str__(self):
return str(self.cargo)
node1 = Node(1)
node2 = Node(2)
node3 = Node(3)
node1.next = node2
node2.next = node3
# Exercise
def printList(node):
print "[",
while node:
print node,
node = node.next
if node != None:
print ",",
print "]",
print
def printBackward(list):
if list == None: return
head = list
tail = list.next
printBackward(tail)
print head,
So let’s say… printBackward(node1) at first, if list should be ignored since node1 contains a reference to node2 so we move to head = list which is node1. tail = list.next which I see as node1.next = node2 so tail = node2. Then we get to printBackward(tail)which is node2. At that point, what happens? Do we do this all over again? I see this going up to node3 which at that point will return None. When do we get to print head,??? We make a recursive call before even getting to the print head,? Please educate me as I’m trying to understand the examples that are given to me within my lesson. Thanks!
You are correct about everything that is happening leading up to when
printBackward(node3)is called. What is going on is every time you get to the recursiveprintBackward()call, you go deeper into the call stack. The finalprintdoesn’t actually get called until the recursion stops callingprintBackward(), and then unwinds. As it returns each time, THEN theprintis called, which is why you get the backwards order. Theprints happen during the unwinding of the call stack.When you get to
node3,tailbecomesNone, and that next call toprintBackwards()is what returns right away, and the printing begins.Also a small note, you are shadowing a few built-in python names (
listandnext).