/
add-two-numbers.cpp
135 lines (100 loc) · 2.52 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
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
/*
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
*/
#include <iostream>
#include <stdlib.h>
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)
{
if (!l1) return l2;
if (!l2) return l1;
ListNode head(0);
ListNode *index = &head;
while (l1 || l2){
index->val += (l1?l1->val:0) + (l2?l2->val:0);
index->next = new ListNode(index->val / 10);
index->val %= 10;
index->next->next = index;
index = index->next;
if (l1) l1 = l1->next;
if (l2) l2 = l2->next;
}
if (!index->val){
index->next->next = NULL;
delete index;
}else
index->next = NULL;
return &head;
}
};
*/
class Solution {
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2)
{
if (!l1) return l2;
if (!l2) return l1;
ListNode *head = l1;
while (l1->next && l2->next){
l1->val += l2->val;
if (l1->val >= 10){
l1->next->val += 1;
l1->val %= 10;
}
l1 = l1->next;
l2 = l2->next;
}
l1->val += l2->val;
if (!l1->next) l1->next = l2->next;
while (l1->val >= 10){
if(l1->next)
l1->next->val += 1;
else
l1->next = new ListNode(1);
l1->val %= 10;
l1 = l1->next;
}
return head;
}
};
void printList(ListNode *head)
{
while (head){
cout << head->val << " ";
head = head->next;
}
cout << endl;
}
int main(int argc, char const *argv[])
{
ListNode test1(6);
ListNode test2(2);
ListNode test3(5);
ListNode test4(4);
ListNode test5(5);
ListNode test6(6);
ListNode test7(9);
test1.next = &test2;
//test2.next = &test3;
//test3.next = &test4;
test4.next = &test5;
test5.next = &test6;
test6.next = &test7;
printList(&test1);
printList(&test4);
Solution a;
printList(a.addTwoNumbers(&test1, &test4));
system("PAUSE");
return 0;
}