0445. 两数相加 II【中等】
1. 📝 题目描述
给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
示例 1:

txt
输入:l1 = [7,2,4,3], l2 = [5,6,4]
输出:[7,8,0,7]1
2
2
示例 2:
txt
输入:l1 = [2,4,3], l2 = [5,6,4]
输出:[8,0,7]1
2
2
示例 3:
txt
输入:l1 = [0], l2 = [0]
输出:[0]1
2
2
提示:
- 链表的长度范围为
[1, 100] 0 <= node.val <= 9- 输入数据保证链表代表的数字无前导 0
进阶:如果输入链表不能翻转该如何解决?
2. 🎯 s.1 - 栈
c
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
int s1[100], s2[100], t1 = 0, t2 = 0;
while (l1) { s1[t1++] = l1->val; l1 = l1->next; }
while (l2) { s2[t2++] = l2->val; l2 = l2->next; }
int carry = 0;
struct ListNode* head = NULL;
while (t1 > 0 || t2 > 0 || carry) {
int sum = carry;
if (t1 > 0) sum += s1[--t1];
if (t2 > 0) sum += s2[--t2];
carry = sum / 10;
struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
node->val = sum % 10;
node->next = head;
head = node;
}
return head;
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
js
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var addTwoNumbers = function (l1, l2) {
const s1 = [],
s2 = []
while (l1) {
s1.push(l1.val)
l1 = l1.next
}
while (l2) {
s2.push(l2.val)
l2 = l2.next
}
let carry = 0,
head = null
while (s1.length || s2.length || carry) {
const sum = (s1.pop() || 0) + (s2.pop() || 0) + carry
carry = Math.floor(sum / 10)
const node = new ListNode(sum % 10)
node.next = head
head = node
}
return head
}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
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
py
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
s1, s2 = [], []
while l1:
s1.append(l1.val)
l1 = l1.next
while l2:
s2.append(l2.val)
l2 = l2.next
carry, head = 0, None
while s1 or s2 or carry:
total = (s1.pop() if s1 else 0) + (s2.pop() if s2 else 0) + carry
carry = total // 10
node = ListNode(total % 10)
node.next = head
head = node
return head1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
- 时间复杂度:
- 空间复杂度:
算法思路:
- 将两个链表分别压入栈,从低位开始相加
- 用头插法构建结果链表,处理进位