-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path2_add_two_numbers.cpp
86 lines (72 loc) · 1.62 KB
/
2_add_two_numbers.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include "test.h"
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
{
ListNode* head = nullptr;
ListNode** pl = &head;
int carry = 0;
while(l1 != nullptr || l2 != nullptr || carry > 0)
{
*pl = new ListNode(carry);
if(l1 != nullptr)
{
(*pl)->val += l1->val;
l1 = l1->next;
}
if(l2 != nullptr)
{
(*pl)->val += l2->val;
l2 = l2->next;
}
carry = (*pl)->val / 10;
(*pl)->val = (*pl)->val % 10;
pl = &((*pl)->next);
}
return head;
}
ListNode* makeList(vector<int> nums)
{
ListNode* head = nullptr;
ListNode** cur = &head;
for(auto n : nums)
{
(*cur) = new ListNode(n);
cur = &((*cur)->next);
}
return head;
}
void printList(ListNode* l)
{
while(l != nullptr)
{
cout << l->val << " -> ";
l = l->next;
}
cout << "null" << endl;
}
};
int main()
{
Solution s;
auto l1 = s.makeList({2,4,5});
auto l2 = s.makeList({5,6,4});
s.printList(l1);
s.printList(l2);
auto ret = s.addTwoNumbers(l1, l2);
s.printList(ret);
}