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

Python递归合并有序链表运行报错:AttributeError问题求助

解决递归合并有序链表时的AttributeError问题

嘿,这个问题我之前也碰到过!你报错的AttributeError: 'list' object has no attribute 'value'原因很明确:你的merge_lists函数是为链表节点对象设计的,但你传入的是Python内置的普通列表。普通列表根本没有value和next这些属性,自然会触发错误。

怎么解决?

我们需要先把普通列表转换成链表结构,再调用你的合并函数,具体步骤如下:

  1. 定义链表节点类
    首先得有一个表示链表节点的类,每个节点需要存储值(value)和指向下一个节点的指针(next):
class ListNode:
    def __init__(self, value=0, next_node=None):
        self.value = value
        self.next = next_node
  1. 编写列表与链表的转换函数
    我们需要把普通列表转成链表,也需要把合并后的链表转回列表方便查看结果:
def list_to_linked_list(arr):
    # 用哑节点简化链表生成逻辑
    dummy = ListNode()
    current = dummy
    for num in arr:
        current.next = ListNode(num)
        current = current.next
    return dummy.next

def linked_list_to_list(head):
    result = []
    current = head
    while current:
        result.append(current.value)
        current = current.next
    return result
  1. 修改调用逻辑,正确传入链表
    你的merge_lists递归逻辑是对的,只需要把普通列表转成链表后再传入:
# 保留你原来的合并函数
def merge_lists(h1, h2):
    if h1 is None:
        return h2
    if h2 is None:
        return h1
    if h1.value < h2.value:
        h1.next = merge_lists(h1.next, h2)
        return h1
    else:
        h2.next = merge_lists(h2.next, h1)
        return h2

# 现在正确生成链表并调用
h1_list = [1,5,7]
h2_list = [2,4,6]
h1 = list_to_linked_list(h1_list)
h2 = list_to_linked_list(h2_list)

merged_head = merge_lists(h1, h2)
# 把合并后的链表转回列表打印
print(linked_list_to_list(merged_head))  # 输出: [1, 2, 4, 5, 6, 7]

为什么这样改?

  • ListNode类是链表的基础单元,你的merge_lists函数正是依赖节点的value和next属性来做递归比较和链接的。
  • list_to_linked_list帮你把普通数组转换成符合要求的链表结构,这样merge_lists才能正确工作。
  • linked_list_to_list则是把链表转回普通列表,让你能直观看到合并后的结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 09:16:19