-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaddTwoNumbers.cpp
More file actions
134 lines (125 loc) · 3.18 KB
/
addTwoNumbers.cpp
File metadata and controls
134 lines (125 loc) · 3.18 KB
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
#include <iostream>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;
/**
* 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)
{
ListNode * Lsum, * psum, * pri;
//initiallize the pointer;
Lsum = new ListNode(0);
pri = Lsum;
psum = Lsum;
int temp = 0;
int AddCount = 0;
while(l1 != NULL && l2 != NULL)
{
temp = l1->val + l2->val + AddCount;
if(temp < 10)
{
pri = psum;
psum->val = temp;
psum->next = new ListNode(0);
psum = psum->next;
AddCount = 0;
}
else
{
pri = psum;
psum->val = temp % 10;
psum->next = new ListNode(0);
psum = psum->next;
AddCount = temp / 10;
}
l1 = l1->next;
l2 = l2->next;
}
if(l1 == NULL && l2 != NULL)//l2 longer
while(l2 != NULL)
{
temp = l2->val + AddCount;
if(temp < 10)
{
pri = psum;
psum->val = temp;
psum->next = new ListNode(0);
psum = psum->next;
AddCount = 0;
}
else
{
pri = psum;
psum->val = temp % 10;
psum->next = new ListNode(0);
psum = psum->next;
AddCount = temp / 10;
}
l2 = l2->next;
}
if(l1 != NULL && l2 == NULL)//l1 longer
while(l1 != NULL)
{
temp = l1->val + AddCount;
if(temp < 10)
{
pri = psum;
psum->val = temp;
psum->next = new ListNode(0);
psum = psum->next;
AddCount = 0;
}
else
{
pri = psum;
psum->val = temp % 10;
psum->next = new ListNode(0);
psum = psum->next;
AddCount = temp / 10;
}
l1 = l1->next;
}
if(l1 == NULL && l2 == NULL && AddCount > 0)
{
pri = psum;
psum->val = AddCount;
psum->next = new ListNode(0);
psum = psum->next;
AddCount = 0;
}
ListNode * ps = psum;
psum = pri;
delete ps;
psum->next = NULL;
return Lsum;
}
};
int main()
{
Solution s;
ListNode * l1, * l2, * result;
l1 = new ListNode(0);
l1->val = 5;
l1->next = NULL;
l2 = new ListNode(0);
l2->val = 5;
l2->next = NULL;
result = s.addTwoNumbers(l1,l2);
while(result != NULL)
{
cout<<result->val<<endl;
result = result->next;
}
return 0;
}