-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadd-two-numbers.cc
77 lines (74 loc) · 1.59 KB
/
add-two-numbers.cc
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <iostream>
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
void Pushback(ListNode** res,int v)
{
if(*res == NULL)
{
*res = new ListNode(v);
return;
}
ListNode* cur = *res;
while(cur->next != NULL)
{
cur = cur->next;
}
cur->next = new ListNode(v);
return;
}
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
ListNode* cur1 = l1;
ListNode* cur2 = l2;
ListNode* res = NULL;
int carry = 0;
while(cur1 != NULL || cur2 != NULL)
{
int sum = 0;
if(cur1 != NULL)
{
sum += cur1->val;
cur1 = cur1->next;
}
if(cur2 != NULL)
{
sum += cur2->val;
cur2 = cur2->next;
}
sum += carry;
if(sum >= 10)
{
sum -= 10;
carry = 1;
}
else
{
carry = 0;
}
Pushback(&res,sum);
}
if(carry == 1)
{
Pushback(&res,1);
}
for(ListNode* cur = res; cur != NULL; cur = cur->next)
{
std::cout<<cur->val<<" ";
}
std::cout<<std::endl;
return res;
}
};
int main()
{
ListNode* l1 = new ListNode(1);
l1->next = new ListNode(8);
ListNode* l2 = new ListNode(0);
Solution s;
s.addTwoNumbers(l1,l2);
return 0;
}