By printing the array "total", I can see that the values are appending correctly. And yet when I print(linked_list_values(a)), it returns None.
a = Node(5)
b = Node(3)
c = Node(9)
total = []
def linked_list_values(head):
print(total)
if head == None:
return None
total.append(head.num)
linked_list_values(head.next)
print(linked_list_values(a))
CodePudding user response:
The function returns None
because you never have a return
statement in it. It does mutate total
, but it gets mutated in-place.
Try printing the value of total
after the function runs.
>>> linked_list_values(a)
None
>>> total
[5, 3, 9] # Assuming a.next == b and b.next == c
CodePudding user response:
Your function isn't returning anything for the statement at the bottom to print meaning Python is gonna read the return value of your function as None. A simple fix would be to add a return statement after the recursive call.
a = Node(5)
b = Node(3)
c = Node(9)
total = []
def linked_list_values(head):
if head == None:
return None
total.append(head.num)
linked_list_values(head.next)
return total
print(linked_list_values(a))