【问题标题】:Function returns None no matter what无论如何,函数都返回 None
【发布时间】:2020-11-28 21:22:55
【问题描述】:

我有这个函数,它应该通过它的索引给出链表节点的值。 我可以打印前一行的值,但是当我返回值时,它会以某种方式变成 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))

输出:

4
3
2
1
None

我什至在函数中返回了一个整数,但它也变成了 None。

任何帮助将不胜感激。

【问题讨论】:

  • 第二个return语句在哪里?
  • 我不明白。我想说的是,我只是输入“return 0”而不是“return head.val”,它返回 None。感谢您的回复。
  • 查看答案...帮助

标签: python return


【解决方案1】:

您还必须返回递归调用:

def index(head, idx=0):
    if idx == 0:
        return head.val
    print(idx)
    return index(head.next, idx - 1)

你错过了最后一行的返回值。

其他功能

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

【讨论】:

  • 哦,我不知道。谢谢你的帮助。
  • 在“create_list”函数中,因为它只是引用它们,所以我没有注意到问题,这让我很困惑。谢谢。
猜你喜欢
  • 1970-01-01
  • 2011-12-23
  • 1970-01-01
  • 2016-03-07
  • 1970-01-01
  • 2020-07-10
  • 2017-01-24
  • 1970-01-01
  • 2014-10-01
相关资源
最近更新 更多