-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1_TwoNumsAdd.cpp
112 lines (94 loc) · 2.63 KB
/
1_TwoNumsAdd.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
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
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
/* ListNode *res,*cur;
cur = res = (ListNode*)malloc(sizeof(ListNode));
if(l1 == NULL && l2 == NULL)return NULL;
else if(l1 == NULL || l2 == NULL)res->next = l1?l1:l2;
else {
int carry = 0;
while(l1&&l2){
ListNode *newNode = (ListNode*)malloc(sizeof(ListNode));
newNode->next = NULL;
cur->next = newNode;
newNode->val = l1->val + l2->val + carry;
if(newNode->val > 9){
carry = 1;
newNode->val %= 10;
}
else carry = 0;
cur = cur->next;
l1 = l1->next;
l2 = l2->next;
}
ListNode *l = l1?l1:l2;
while(l||carry)
{
ListNode *newNode = (ListNode*)malloc(sizeof(ListNode));
newNode->next = NULL;
cur->next = newNode;
if(l)newNode->val = l->val + carry;
else newNode->val = 1;
if(newNode->val > 9){
carry = 1;
newNode->val %= 10;
}
else carry = 0;
cur = cur->next;
if(l)l = l->next;
}
}
return res->next;
*/
ListNode *res, *cur;
res = cur = (ListNode*)malloc(sizeof(ListNode));
res->next = NULL;
int carry = 0;
while(!l1 || !l2){
printf("!\n");
int x1 = l1?l1->val:0;
int x2 = l2?l2->val:0;
cur->next = (ListNode*)malloc(sizeof(ListNode));
if(cur->next)cur->next->next = NULL;
cur->next->val = x1 + x2 + carry;
if(cur->next->val > 9){
carry = 1;
cur->next->val %= cur->next->val;
}else{
carry = 0;
}
cur = cur->next;
if(l1)l1 = l1->next;
if(l2)l2 = l2->next;
}
return res->next;
}
};
int main()
{
ListNode n1(1);
ListNode n2(8);
ListNode n3(3);
ListNode n4(0);
ListNode n5(9);
ListNode n6(9);
n1.next = &n2;
n2.next = &n3;
n4.next = &n5;
n5.next = &n6;
Solution s;
ListNode *res = s.addTwoNumbers(&n1,&n4);
while(res)
{
printf("%d",res->val);
res = res->next;
}
return 0;
}