0

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.

wjandrea
34k10 gold badges69 silver badges107 bronze badges
asked Nov 28, 2020 at 21:22
3
  • Where is the second return statement? Commented Nov 28, 2020 at 21:24
  • I don't understand.What I was trying to say was that instead of "return head.val" I just put "return 0" and it returned None.Thanks for responding. Commented Nov 28, 2020 at 21:26
  • See answer ... help Commented Nov 28, 2020 at 21:27

1 Answer 1

1

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
answered Nov 28, 2020 at 21:25
Sign up to request clarification or add additional context in comments.

2 Comments

Oh I didn't know that.Thanks for the help.
Well in the "create_list" function since it just references them I didn't notice the problem and that kinda confused me. Thanks.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.