-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path2.cpp
43 lines (39 loc) · 834 Bytes
/
2.cpp
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
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* p1 = l1;
ListNode* p2 = l2;
ListNode* res = new ListNode((p1->val + p2->val) % 10);
ListNode* head = res;
int c = (p1->val + p2->val) / 10;
p1 = p1->next;
p2 = p2->next;
while (p1 != NULL || p2 != NULL) {
int x = c;
if (p1 != NULL) {
x += p1->val;
p1 = p1->next;
}
if (p2 != NULL) {
x += p2->val;
p2 = p2->next;
}
c = x / 10;
ListNode* buff = new ListNode(x % 10);
res->next = buff;
res = res->next;
}
if (c > 0) {
ListNode* buff = new ListNode(c);
res->next = buff;
}
return head;
}
};