forked from zhuli19901106/leetcode-zhuli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadd-two-numbers_1_AC.cpp
54 lines (52 loc) · 1.31 KB
/
add-two-numbers_1_AC.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
44
45
46
47
48
49
50
51
52
53
54
/**
* 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) {
static const int R = 10;
ListNode *p1, *p2, *p3;
ListNode *h3, *t3;
p1 = l1;
p2 = l2;
h3 = t3 = NULL;
while (p1 != NULL && p2 != NULL) {
p3 = new ListNode(p1->val + p2->val);
if (t3 == NULL) {
h3 = t3 = p3;
} else {
t3->next = p3;
t3 = p3;
}
p1 = p1->next;
p2 = p2->next;
}
while (p1 != NULL) {
t3->next = new ListNode(p1->val);
t3 = t3->next;
p1 = p1->next;
}
while (p2 != NULL) {
t3->next = new ListNode(p2->val);
t3 = t3->next;
p2 = p2->next;
}
p3 = h3;
while (p3->next != NULL) {
p3->next->val += p3->val / R;
p3->val %= R;
p3 = p3->next;
}
while (p3->next == NULL && p3->val >= R) {
p3->next = new ListNode(p3->val / R);
p3->val %= R;
p3 = p3->next;
}
return h3;
}
};