归档

2. 两数相加

2. 两数相加

题目

描述:

给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。

请你将两个数相加,并以相同形式返回一个表示和的链表。

你可以假设除了数字 0 之外,这两个数都不会以 0 开头。

示例 1:

示例1图片

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

示例 2:

  • 输入: l1 = [0], l2 = [0]
  • 输出: [0]

示例 3:

  • 输入: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
  • 输出: [8,9,9,9,0,0,0,1]

提示:

  • 每个链表中的节点数在范围 [1, 100] 内
  • 0 <= Node.val <= 9
  • 题目数据保证列表表示的数字不含前导零

题解

从个位开始模拟加法

链表按低位在前保存数字,例如 [2,4,3] 表示 342,头节点是个位。沿着 next 前进,正好对应手算从个位向高位的顺序。每轮取两个当前位和上一轮的进位相加,结果当前位为 sum % 10,传给下一位的进位为 sum / 10。

例如 [2,4,3] 与 [5,6,4]:个位 2 + 5 = 7;十位 4 + 6 = 10,写 0、进 1;百位 3 + 4 + 1 = 8。得到 [7,0,8],表示 807。每位最多 9 + 9 + 1 = 19,因此进位只可能是 0 或 1。

长度不同也不必补齐输入链表,已经走完的一侧按 0 参与计算。例如 [9,9,9] 加 [1],每轮得到的当前位都是 0,进位持续为 1;两个链表都走完后还要再生成一个值为 1 的节点,结果为 [0,0,0,1]。因此循环条件使用“任一链表未结束,或者仍有进位”。

结果链表用哑节点维护:dummy 是不属于答案的辅助头节点,有了它,第一个结果节点也能用同一套尾插逻辑接上,不必单独处理。cur 始终指向结果尾部。每次创建一个结果节点,连接到 cur.next 后推进 cur,最后返回 dummy.next。推进 l1、l2 只是改变方法内的引用变量,不会修改原链表节点或连接关系。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    ListNode dummy = new ListNode(0);
    ListNode cur = dummy;
    int carry = 0;

    while (l1 != null || l2 != null || carry != 0) {
        int x = (l1 != null) ? l1.val : 0;
        int y = (l2 != null) ? l2.val : 0;
        int sum = x + y + carry;
        carry = sum / 10;

        cur.next = new ListNode(sum % 10);
        cur = cur.next;

        if (l1 != null) l1 = l1.next;
        if (l2 != null) l2 = l2.next;
    }

    return dummy.next;
}

时间复杂度是 $O(\max(m,n))$,其中 m 和 n 是两个链表长度;额外空间复杂度是 $O(1)$(不计返回结果链表本身)。

输出最多包含 max(m,n) + 1 个节点,因此若把返回结果也计入空间,总空间为 O(max(m,n))。两个输入都表示零时,仍会生成一个值为 0 的结果节点。

完整示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
public class Main {
    public static class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) {
            this.val = val;
        }
        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummyHead = new ListNode(0);
        ListNode curr = dummyHead;
        int carry = 0;
        while (l1 != null || l2 != null || carry != 0) {
            int val1 = (l1 != null) ? l1.val : 0;
            int val2 = (l2 != null) ? l2.val : 0;
            int sum = val1 + val2 + carry;
            carry = sum / 10;
            curr.next = new ListNode(sum % 10);
            curr = curr.next;
            if (l1 != null) {
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }
        }
        return dummyHead.next;
    }
    public static ListNode createList(int[] arr) {
        ListNode dummy = new ListNode(0);
        ListNode curr = dummy;
        for (int val : arr) {
            curr.next = new ListNode(val);
            curr = curr.next;
        }
        return dummy.next;
    }
    public static void printList(ListNode head) {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        while (head != null) {
            sb.append(head.val);
            if (head.next != null) {
                sb.append(", ");
            }
            head = head.next;
        }
        sb.append("]");
        System.out.println(sb.toString());
    }
    public static void main(String[] args) {
        int[] arr1 = {2, 4, 3};
        int[] arr2 = {5, 6, 4};
        ListNode l1 = createList(arr1);
        ListNode l2 = createList(arr2);
        System.out.println("示例 1 输入:");
        System.out.print("l1 = ");
        printList(l1);
        System.out.print("l2 = ");
        printList(l2);
        ListNode res1 = addTwoNumbers(l1, l2);
        System.out.print("示例 1 输出: ");
        printList(res1);
        System.out.println("-----------------------------");
        int[] arr3 = {0};
        int[] arr4 = {0};
        ListNode l3 = createList(arr3);
        ListNode l4 = createList(arr4);
        System.out.println("示例 2 输入:");
        System.out.print("l1 = ");
        printList(l3);
        System.out.print("l2 = ");
        printList(l4);
        ListNode res2 = addTwoNumbers(l3, l4);
        System.out.print("示例 2 输出: ");
        printList(res2);
        System.out.println("-----------------------------");
        int[] arr5 = {9, 9, 9, 9, 9, 9, 9};
        int[] arr6 = {9, 9, 9, 9};
        ListNode l5 = createList(arr5);
        ListNode l6 = createList(arr6);
        System.out.println("示例 3 输入:");
        System.out.print("l1 = ");
        printList(l5);
        System.out.print("l2 = ");
        printList(l6);
        ListNode res3 = addTwoNumbers(l5, l6);
        System.out.print("示例 3 输出: ");
        printList(res3);
    }
}

运行结果(OpenJDK 21.0.12):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
示例 1 输入:
l1 = [2, 4, 3]
l2 = [5, 6, 4]
示例 1 输出: [7, 0, 8]
-----------------------------
示例 2 输入:
l1 = [0]
l2 = [0]
示例 2 输出: [0]
-----------------------------
示例 3 输入:
l1 = [9, 9, 9, 9, 9, 9, 9]
l2 = [9, 9, 9, 9]
示例 3 输出: [8, 9, 9, 9, 0, 0, 0, 1]
本文由作者按照 CC BY 4.0 进行授权