⚡Flashcard Drill➔
NeetCode #328LC-445MediumLinked List
← Back to All Problems

#328 · #445 · Add Two Numbers II(两数相加 II)

📌 Problem Statement & Constraints

You are given two non-empty linked lists representing two non-negative integers in most significant first order. Add the two numbers and return the sum as a linked list in the same order. You may not reverse the input lists. Constraints: the number of nodes in each list is in [1, 100], 0 <= Node.val <= 9.

💡 Core Algorithmic Approaches

  1. Because the digits are most-significant-first, the carry propagates from the tail -- which is the hard direction for a singly linked list.
  2. Two clean options: reverse both lists, add as in Add Two Numbers, then reverse the result; or push both lists onto stacks and pop digits.
  3. The problem says you may not reverse the input lists; the first option reverses them destructively, which some interpretations forbid. The stack version avoids that entirely.
  4. Either way the algorithm is O(m + n) time.

💻 Benchmark Python3 Implementation

class Solution:
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        # stack-based: avoids mutating the inputs
        s1, s2 = [], []
        cur = l1
        while cur:
            s1.append(cur.val)
            cur = cur.next
        cur = l2
        while cur:
            s2.append(cur.val)
            cur = cur.next
        carry = 0
        head = None
        while s1 or s2 or carry:
            total = carry
            if s1:
                total += s1.pop()
            if s2:
                total += s2.pop()
            # build the result from the least significant digit, prepending
            node = ListNode(total % 10)
            node.next = head
            head = node
            carry = total // 10
        return head

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(m + n): each digit is pushed and popped once.
💾 Space Complexity
O(m + n) for the two stacks (the reverse-and-add variant uses O(1) extra beyond the output but mutates the inputs).

⚠️ Interview Pitfalls & Follow-ups

  • Building the result in the wrong direction: since the digits are processed least-significant-first, each new node must be prepended to the result.
  • Mutating the input lists: the reverse-and-add approach reverses the inputs in place, which the problem forbids.
  • Forgetting the final carry: [5] + [5] must produce [1, 0].
  • Assuming equal lengths: the lists may differ, so each stack needs its own emptiness check.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Linked List Problems

中文速览与面试要点

两数相加 II

给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。你可以假设除了数字 0 之外,这两个数字都不会以零开头。进阶:如果输入链表不能修改该如何处理?换句话说,你不能对列表中的节点进行翻转。约束:每个链表的节点数在范围 [1, 100] 内;0 ≤ Node.val ≤ 9;输入数据保证数字不含前导零(除数字 0 本身)。

核心要点

  • 栈 + 头插(标准解) :由于数字是 高位在前 ,而加法必须从低位开始,因此把两个链表分别压入栈,然后逐位弹出相加(即从低位到高位)。
  • 头插构造结果 :每次算出一位数后,用 ListNode(digit, res) 插入到结果链表的头部,这样最终结果的顺序就是高位在前。
  • 为什么不能像 2 题那样直接遍历 :2 题的数字是低位在前,可以直接从头遍历;本题需要栈来反转顺序。
  • 不修改输入 :栈方案只读取节点值,不修改任何指针,满足进阶要求。

常见陷阱

  • 反转链表后再相加 :可行但会修改输入,不满足进阶要求(题目明确说「不能对节点进行翻转」)。
  • 循环条件漏掉 carry :最高位相加可能产生进位,需要额外节点。
  • 用尾插构造结果 :会得到低位在前的链表,与题目要求相反。必须用头插。
  • 把结果存成整数 :链表长度可达 100 位,整数会溢出(C++/Java)。
  • 栈为空时忘记补 0 :两个链表长度不等时必须用 if s1 else 0 。

参考实现

class Solution:
    def addTwoNumbers(self, l1: 'ListNode', l2: 'ListNode') -> 'ListNode':
        # ① 把两个链表的值压入栈(栈顶为最低位)
        s1, s2 = [], []
        while l1:
            s1.append(l1.val)
            l1 = l1.next
        while l2:
            s2.append(l2.val)
            l2 = l2.next

        # ② 从低位到高位相加,用头插构造结果
        carry = 0
        res = None
        while s1 or s2 or carry:
            a = s1.pop() if s1 else 0
            b = s2.pop() if s2 else 0
            carry, digit = divmod(a + b + carry, 10)
            res = ListNode(digit, res)      # 头插,使结果高位在前
        return res