-
Notifications
You must be signed in to change notification settings - Fork 481
/
Add_Two_Numbers.cpp
83 lines (81 loc) · 1.65 KB
/
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
#include <iostream>
// Definition for singly-linked list.
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
};
class Solution
{
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
{
ListNode* dumHead = new ListNode(0);
ListNode* p = dumHead;
int add = 0;
while (l1 || l2 || add)
{
int val = get_value(l1) + get_value(l2) + add;
add = val / 10;
p->next = new ListNode(val % 10);
p = p->next;
l1 = get_p(l1);
l2 = get_p(l2);
}
ListNode* ret = dumHead->next;
delete dumHead;
return ret;
}
private:
int get_value(ListNode* l)
{
if (l != nullptr)
{
return l->val;
}
else
{
return 0;
}
}
ListNode* get_p(ListNode* l)
{
if (l != nullptr)
{
return l->next;
}
else
{
return nullptr;
}
}
};
void deleteListNode(ListNode *l1)
{
while (l1 != nullptr)
{
ListNode* p = l1->next;
delete l1;
l1 = p;
}
}
int main()
{
ListNode *l1 = new ListNode(0);
l1->next = new ListNode(4);
l1->next->next = new ListNode(3);
ListNode *l2 = new ListNode(0);
l2->next = new ListNode(6);
l2->next->next = new ListNode(4);
ListNode * ret = Solution().addTwoNumbers(l1, l2);
while (ret != nullptr)
{
std::cout << ret->val << std::endl;
ret = ret->next;
}
deleteListNode(l1);
deleteListNode(l2);
deleteListNode(ret);
return 0;
}