Reputation:
I have this function which is supposed to give the value of a linked list node by its index. I can print the value the line before but when I return the value it somehow turns into None.
class ListNode:
def __init__(self, val=0, next_node=None):
self.val = val
self.next = next_node
def create_list(linkedlist, i, j=1):
if i == 0:
return
l = ListNode(j)
linkedlist.next = l
create_list(linkedlist.next, i-1, j+1)
def index(head, idx=0):
if idx == 0:
return head.val
print(idx)
index(head.next, idx-1)
link = ListNode()
create_list(link, 5)
print(index(link, 4))
Output:
4
3
2
1
None
I even returned an integer in the function but that turned into None as well.
Any help would be much appreciated.
Upvotes: 0
Views: 85
Reputation: 27311
You have to return the recursive call as well:
def index(head, idx=0):
if idx == 0:
return head.val
print(idx)
return index(head.next, idx - 1)
You're missing the return on the last line.
For the other function
def create_list(linkedlist,i,j=1):
if i == 0:
return linkedlist # missing object to return in terminal case
l = ListNode(j)
linkedlist.next = l
return create_list(linkedlist.next,i-1,j+1) # missing return on recursive call
Upvotes: 1