-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddTwoNumbers.cpp
More file actions
154 lines (83 loc) · 2.45 KB
/
Copy pathAddTwoNumbers.cpp
File metadata and controls
154 lines (83 loc) · 2.45 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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
#include <iostream>
#include <algorithm>
#include <list>
using namespace std;
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
if (l1==NULL && l2 == NULL)
return NULL;
int v1 = 0;
int v2 = 0;
if (l1!=NULL)
v1= l1->val;
if(l2!=NULL)
v2=l2->val;
cout<<"l1.val:"<<v1<<"l2.val:"<<v2<<endl;
int sumDigit = (v1+v2)%10;
int carry = (v1+v2)/10;
cout<<"carry:"<<carry<<endl;
if (l1->next !=NULL){
l1->next->val = l1->next->val+carry;
}
else
{
if (l2->next !=NULL)
l2->next->val = l2->next->val+carry;
}
ListNode* pnode = new ListNode(sumDigit);
if (l1->next ==NULL && l2->next ==NULL && carry>0)
{
ListNode* pNext = new ListNode(carry);
pnode->next = pNext;
}
if (l1->next !=NULL && l2->next !=NULL)
pnode->next = addTwoNumbers(l1->next, l2->next);
if (l1->next ==NULL && l2->next !=NULL)
pnode->next = l2->next;
if (l2->next ==NULL && l1->next !=NULL)
pnode->next = l1->next;
return pnode;
}
};
int main(){
ListNode l1(1);
//ListNode v2(8);
// l1.next = &v2;
// ListNode v3(3);
// v2.next = &v3;
ListNode l2(9);
ListNode v22(9);
l2.next = &v22;
ListNode v32(4);
// v22.next = &v32;
Solution s;
ListNode *res = s.addTwoNumbers(&l1,&l2);
ListNode *runner = res;
while (runner !=NULL)
{
cout<<(*runner).val<<endl;
runner =(*runner).next;
}
/* ListNode *runner = &l2;
while (runner !=NULL)
{
cout<<(*runner).val<<endl;
runner =(*runner).next;
}
*/
return 0;
}