Skip to content

Commit 15db996

Browse files
committed
AddTwoNumbers.cpp
1 parent b81ad16 commit 15db996

1 file changed

Lines changed: 40 additions & 0 deletions

File tree

LeetCode/AddTwoNumbers.cpp

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
#include <iostream>
2+
using namespace std;
3+
4+
struct ListNode {
5+
int val;
6+
ListNode *next;
7+
ListNode(int x) : val(x), next(NULL) {}
8+
};
9+
10+
class Solution {
11+
public:
12+
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
13+
int add = 0;
14+
ListNode *ret(NULL), *cur(NULL);
15+
while (true) {
16+
int s = add;
17+
if (ret == NULL) {
18+
s += l1->val + l2->val;
19+
} else {
20+
if (l1 != NULL) s += l1->val;
21+
if (l2 != NULL) s += l2->val;
22+
}
23+
ListNode *t = new ListNode(s % 10);
24+
add = s / 10;
25+
26+
if (ret == NULL) ret = t;
27+
else cur->next = t;
28+
cur = t;
29+
30+
if (l1 != NULL) l1 = l1->next;
31+
if (l2 != NULL) l2 = l2->next;
32+
if (l1 == NULL && l2 == NULL) break;
33+
}
34+
if (add == 1) {
35+
ListNode *t = new ListNode(1);
36+
cur->next = t;
37+
}
38+
return ret;
39+
}
40+
};

0 commit comments

Comments
 (0)