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

LeetCode两数相加报错:ListNode与int无法执行乘法运算

问题分析与修复

错误原因

  • 循环条件错误:你用l1.val != None作为循环终止条件,但ListNode的val默认是0,且节点存在时val不会是None,正确的终止条件应该是判断l1本身是否为None。
  • 指针赋值错误:代码中l1.val = l1.next是把当前节点的val属性替换成了下一个ListNode对象,导致下一次循环时l1.val不再是整数,而是ListNode实例,自然无法和整数mult做乘法运算,这就是报错的直接原因。正确的做法是移动链表指针本身:l1 = l1.next。

修正后的基础版本代码

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        def list_to_num(node):
            num = 0
            mult = 1
            while node:
                num += node.val * mult
                mult *= 10
                node = node.next
            return num
        
        total = list_to_num(l1) + list_to_num(l2)
        
        # 将总和转回链表
        dummy = ListNode(0)
        current = dummy
        if total == 0:
            return dummy
        while total > 0:
            current.next = ListNode(total % 10)
            total = total // 10
            current = current.next
        return dummy.next

额外提醒

这种将链表转数字的方法存在整数溢出风险(虽然Python的int支持任意精度,但LeetCode的标准解法更推荐直接模拟加法进位,逐位相加构建结果链表,避免转换数字的步骤)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 07:05:13