-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdd-Two-Numbers-II.cpp
More file actions
42 lines (41 loc) · 1.2 KB
/
Copy pathAdd-Two-Numbers-II.cpp
File metadata and controls
42 lines (41 loc) · 1.2 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
// Leetcode 445
/**
* 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* reverse(ListNode* head){
ListNode* prev = NULL;
while(head){
ListNode* next = head->next;
head->next = prev;
prev = head;
head = next;
}
return prev;
}
ListNode* solve(ListNode* l1, ListNode* l2, int carry){
// base case
if(!l1 && !l2 && carry==0) return NULL;
int first = l1 ? l1->val : 0, second = l2 ? l2->val : 0;
int sum = (first + second + carry);
int rem = sum % 10;
carry = sum / 10;
ListNode* head = new ListNode(rem);
head->next = solve(l1 ? l1->next : NULL, l2 ? l2->next : NULL, carry);
return head;
}
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* l1rev = reverse(l1);
ListNode* l2rev = reverse(l2);
ListNode* sumrev = solve(l1rev, l2rev, 0);
return reverse(sumrev);
}
};