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
user13406539
-
Where is the second return statement?adir abargil– adir abargil2020年11月28日 21:24:09 +00:00Commented 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.user13406539– user134065392020年11月28日 21:26:40 +00:00Commented Nov 28, 2020 at 21:26
-
See answer ... helpadir abargil– adir abargil2020年11月28日 21:27:31 +00:00Commented Nov 28, 2020 at 21:27
1 Answer 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
thebjorn
27.6k12 gold badges107 silver badges152 bronze badges
Sign up to request clarification or add additional context in comments.
lang-py