445 两数相加 II

本文最后更新于:2021年1月21日 下午

给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。

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

进阶:

如果输入链表不能修改该如何处理?换句话说,你不能对列表中的节点进行翻转。

示例:

1
2
输入:(7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 8 -> 0 -> 7

Solution

  • 先翻转,在求和。参考 [2 两数相加]
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
// @lc code=start
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
l1 = reverse(l1);
l2 = reverse(l2);
ListNode* dummyHead = new ListNode(-1), *cur=dummyHead;
int carry = 0;
while(l1 || l2){
int n1 = l1 ? l1->val : 0;
int n2 = l2 ? l2->val : 0;
int sum = n1+n2+carry;
cur->next = new ListNode(sum%10);
cur = cur->next;
carry = sum/10;
if(l1)
l1 = l1->next;
if(l2)
l2 = l2->next;
}
if(carry)
cur->next = new ListNode(carry);
return reverse(dummyHead->next);
}
private:
ListNode* reverse(ListNode* node){
if(!node->next) return node;
ListNode* ret = reverse(node->next);
node->next->next = node;
node->next = NULL;
return ret;
}
};
// @lc code=end
  • 利用栈分别存储链表节点,参考 liuyubobobo
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
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
stack<ListNode*> stack1, stack2, stack;
ListNode* node = l1;
while(node){
stack1.push(node);
node = node->next;
}
node = l2;
while(node){
stack2.push(node);
node = node->next;
}

int carry = 0;
while(!stack1.empty() || !stack2.empty() || carry){
int sum = 0;
if(!stack1.empty()){
sum += stack1.top()->val;
stack1.pop();
}
if(!stack2.empty()){
sum += stack2.top()->val;
stack2.pop();
}
sum += carry;
stack.push(new ListNode(sum%10));
carry = sum/10;
}
ListNode* ret = stack.top(), *cur = ret;
stack.pop();
while(!stack.empty()){
cur->next = stack.top();
cur = cur->next;
stack.pop();
}
return ret;
}
};

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!