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

关于LeetCode中链表实现两数相加问题的技术咨询

问题:LeetCode 两数相加(链表实现)

Hey there! Let's tackle this LeetCode problem together—adding two numbers represented by reversed linked lists. First, let's recap the problem clearly:

给定两个非空链表,分别表示两个非负整数。数字以逆序存储,每个节点包含一个数字。将这两个数相加并以链表形式返回。可以假设除了数字0本身外,这两个数都没有前导零。
示例输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
示例输出:(7 -> 0 -> 8) (对应整数342 + 465 = 807,逆序后即为7->0->8)

I’m guessing you might have run into common pitfalls like handling different-length linked lists, passing carry values correctly, or avoiding null pointer errors when building the result. Let’s walk through a solid solution with explanations:

核心思路

  1. 用**虚拟头节点(dummy head)**简化结果链表的构建,不用单独处理头节点的特殊情况
  2. 同步遍历两个输入链表,每次取当前节点的数值(链表遍历完就用0代替)
  3. 计算当前位总和:总和 = 链表1当前值 + 链表2当前值 + 上一位进位
  4. 当前位的数字是总和 % 10,新的进位是总和 // 10
  5. 将当前位数字作为新节点添加到结果链表
  6. 遍历结束后,如果还有剩余进位,要额外添加一个节点存储这个进位

代码实现(Python 版本)

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def addTwoNumbers(l1: ListNode, l2: ListNode) -> ListNode:
    # 虚拟头节点,方便后续返回结果链表的头
    dummy = ListNode(0)
    current = dummy
    carry = 0
    
    # 循环条件:只要还有未遍历的节点,或者还有进位
    while l1 is not None or l2 is not None or carry != 0:
        # 取当前节点的值,为空则用0代替
        val1 = l1.val if l1 else 0
        val2 = l2.val if l2 else 0
        
        # 计算总和与新的进位
        total = val1 + val2 + carry
        carry = total // 10
        current_digit = total % 10
        
        # 添加新节点到结果链表
        current.next = ListNode(current_digit)
        current = current.next
        
        # 移动链表指针到下一个节点
        if l1:
            l1 = l1.next
        if l2:
            l2 = l2.next
    
    # 虚拟头节点的下一个节点就是结果的头
    return dummy.next

关键细节说明

  • 虚拟头节点:dummy节点让我们不用在开头判断“结果链表是否为空”,直接从dummy.next就能拿到最终的结果头,简化了逻辑。
  • 循环条件:l1 is not None or l2 is not None or carry != 0——这个条件覆盖了所有情况:哪怕两个链表都遍历完了,只要还有进位(比如999 + 1 = 1000),我们就要额外添加一个存1的节点。
  • 长短链表处理:当其中一个链表先遍历完时,用0代替它的当前值,这样就不用写额外的分支来处理长度不同的情况。

If you have specific issues (like a test case failing, or a runtime error), feel free to share the details and we can debug it together!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:21:57