You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为什么我的linked_list_values函数无法返回值列表?

问题原因

你的递归函数linked_list_values虽然正确把节点值追加到了全局数组total里,但函数本身没有返回这个数组:

  • 当递归到head == None时,你返回的是None,而非填充好的total;
  • 递归调用linked_list_values(head.next)后,没有将结果或total返回给上层调用;
  • Python中函数如果没有显式写return语句,默认返回None,所以print(linked_list_values(a))会输出None。

另外你的代码里漏了设置链表的next指针,否则链表只有a一个节点,需要补充a.next = b和b.next = c才能形成完整链表。

修复方案

方案1:修改现有函数,返回全局数组

调整函数的返回逻辑,让递归结束后返回total:

class Node:
    def __init__(self, num):
        self.num = num
        self.next = None

a = Node(5)
b = Node(3)
c = Node(9)
a.next = b
b.next = c

total = []
def linked_list_values(head):
    print(total)
    if head == None:
        return total  # base case返回填充好的数组
    total.append(head.num)
    linked_list_values(head.next)
    return total  # 递归后返回数组

print(linked_list_values(a))  # 输出 [5, 3, 9]

方案2:避免全局变量(推荐)

全局变量会导致多次调用函数时数组残留旧值,更规范的写法是把数组作为递归参数传递:

class Node:
    def __init__(self, num):
        self.num = num
        self.next = None

a = Node(5)
b = Node(3)
c = Node(9)
a.next = b
b.next = c

def linked_list_values(head, total=None):
    # 第一次调用时初始化数组
    if total is None:
        total = []
    if head is None:
        return total
    total.append(head.num)
    # 递归调用时传递数组,并返回结果
    return linked_list_values(head.next, total)

print(linked_list_values(a))  # 输出 [5, 3, 9]

内容的提问来源于stack exchange,提问作者Steve

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 11:30:49