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

LeetCode两数相加问题报错:TypeError: 'ListNode' object is not iterable

两数相加(Add Two Numbers)问题排查与修复

问题背景

在LeetCode练习「两数相加」算法题,题目要求对两个以反向链表形式表示的整数相加,返回结果的反向链表。示例:

输入: l1 = [2,4,3], l2 = [5,6,4]
输出: [7,0,8]
解释: 342 + 465 = 807

本地在Jupyter Notebook用列表测试代码完全正常,但提交到LeetCode时触发报错:

TypeError: 'ListNode' object is not iterable
    for index,i in enumerate(l1):
Line 5 in addTwoNumbers (Solution.py)
    ret = Solution().addTwoNumbers(param_1, param_2)
Line 35 in _driver (Solution.py)
    _driver()
Line 45 in <module> (Solution.py)

原代码如下:

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        list1 = 0
        list2 = 0
        for index,i in enumerate(l1):
            list1+=i*(10**(index))
        for index,i in enumerate(l2):
            list2+=i*(10**(index))
        list3 = list1+list2
        return [int(i) for i in str(list3)][::-1]

错误原因

你在Jupyter测试时传入的是普通列表,但LeetCode实际传入的参数是ListNode对象——这是LeetCode定义的链表节点类,没有实现迭代器协议,不能直接用enumerate()或for循环遍历,因此触发了「不可迭代」的类型错误。另外原代码返回的是列表,而LeetCode要求返回ListNode实例,这也是后续会触发的问题。

修复方案

方式1:适配链表输入输出(兼容原思路)

先把ListNode转成普通列表计算,再把结果转回ListNode返回:

class Solution(object):
    def _node_to_list(self, node):
        # 辅助函数:把ListNode转成普通列表
        res = []
        while node:
            res.append(node.val)
            node = node.next
        return res
    
    def addTwoNumbers(self, l1, l2):
        list1 = self._node_to_list(l1)
        list2 = self._node_to_list(l2)
        
        num1 = 0
        num2 = 0
        for idx, val in enumerate(list1):
            num1 += val * (10 ** idx)
        for idx, val in enumerate(list2):
            num2 += val * (10 ** idx)
        
        total = num1 + num2
        # 把结果转成ListNode返回
        dummy = ListNode(0)
        current = dummy
        # 处理total为0的特殊情况
        if total == 0:
            return dummy
        while total > 0:
            current.next = ListNode(total % 10)
            total = total // 10
            current = current.next
        return dummy.next

方式2:直接操作链表(推荐,避免大数溢出)

如果输入的链表长度很长,转成整数会触发溢出问题,直接遍历链表逐位相加是更稳妥的解法:

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        # 用dummy节点简化链表头的处理
        dummy = ListNode(0)
        current = dummy
        carry = 0  # 记录进位
        
        # 遍历两个链表,直到都遍历完且没有进位
        while l1 or l2 or carry:
            # 取当前节点的值,为空则取0
            val1 = l1.val if l1 else 0
            val2 = l2.val if l2 else 0
            
            total = val1 + val2 + carry
            carry = total // 10  # 更新进位
            current.next = ListNode(total % 10)  # 当前位的结果
            current = current.next
            
            # 移动到下一个节点
            if l1:
                l1 = l1.next
            if l2:
                l2 = l2.next
        
        return dummy.next

关键注意事项

  • LeetCode的输入是ListNode实例,必须通过.val获取节点值,.next访问下一个节点,不能直接当作列表遍历
  • 输出必须是ListNode实例,不能返回普通列表,否则会触发类型错误
  • 大数场景下,转整数的解法会溢出,直接操作链表是符合题目设计意图的最优解

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 03:51:41