-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0445-add-two-numbers-ii.cpp
More file actions
50 lines (47 loc) · 1.31 KB
/
Copy path0445-add-two-numbers-ii.cpp
File metadata and controls
50 lines (47 loc) · 1.31 KB
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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
auto rev = [&](ListNode* lst) {
ListNode* prev = nullptr;
ListNode* cur = lst;
while (cur != nullptr) {
ListNode* temp = cur -> next;
cur -> next = prev;
prev = cur;
cur = temp;
}
return prev;
};
l1 = rev(l1);
l2 = rev(l2);
int s = 0, carry = 0;
ListNode* ans = new ListNode();
while (l1 || l2) {
if (l1 != nullptr) {
s += l1 -> val;
l1 = l1 -> next;
}
if (l2 != nullptr) {
s += l2 -> val;
l2 = l2 -> next;
}
ans -> val = s % 10;
carry = s / 10;
ListNode* head = new ListNode(carry);
head -> next = ans;
ans = head;
s = carry;
}
return carry == 0 ? ans -> next : ans;
}
};