forked from mandliya/algorithms_and_data_structures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
add_two_numbers_lists.cpp
107 lines (94 loc) · 2.28 KB
/
add_two_numbers_lists.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
/*
* We have two numbers represented by a linked list,
* where each node contains a single digit. The digits are stored in reverse order,
* such that the 1's digit is at the head of the list.
* Write a function that adds the two numbers and returns the sum as a linked list.
*
* Example
* Given 7->1->6 + 5->9->2. That is, 617 + 295.
*
* Return 2->1->9. That is 912.
*
* Given 3->1->5 and 5->9->2, return 8->0->8.
*/
#include <iostream>
struct ListNode {
int val;
ListNode *next;
ListNode(int v): val(v), next(nullptr)
{ }
};
ListNode * addLists( ListNode * list1, ListNode *list2 )
{
ListNode *list3 = nullptr;
ListNode *curr = nullptr;
int carry = 0;
while ( list1 && list2 ) {
int x = list1->val + list2->val + carry;
if ( x > 9 ) {
carry = x / 10;
x %= 10;
} else {
carry = 0;
}
if (list3 == nullptr) {
list3 = new ListNode(x);
curr = list3;
} else {
curr->next = new ListNode(x);
curr = curr->next;
}
list1 = list1->next;
list2 = list2->next;
}
while(list1) {
int x = list1->val + carry;
if ( x > 9 ) {
carry = x / 10;
x %= 10;
} else {
carry = 0;
}
curr->next = new ListNode(x);
curr = curr->next;
list1 = list1->next;
}
while(list2) {
int x = list2->val + carry;
if ( x > 9 ) {
carry = x / 10;
x %= 10;
} else {
carry = 0;
}
curr->next = new ListNode(x);
curr = curr->next;
list2 = list2->next;
}
if (carry > 0) {
curr->next = new ListNode(carry);
curr = curr->next;
}
return list3;
}
void iterate(ListNode *node) {
while (node) {
std::cout << node->val << " ";
node = node->next;
}
std::cout << std::endl;
}
int main()
{
ListNode *list1, *list2;
list1 = new ListNode(9);
list1->next = new ListNode(9);
list2 = new ListNode(5);
list2->next = new ListNode(9);
list2->next->next = new ListNode(2);
iterate(list1);
iterate(list2);
ListNode *list3 = addLists(list1, list2);
iterate(list3);
return 0;
}