-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSumOfTwoSingleDigitLinkList.cpp
111 lines (85 loc) · 2.16 KB
/
SumOfTwoSingleDigitLinkList.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
#include <iostream>
/*
Program limitation : Size of both the linked list should be same.
*/
struct Node
{
Node* next;
int data;
};
void Append(Node **head, int data)
{
Node* temp = new Node();
temp->data = data;
temp->next = nullptr;
if (*head == nullptr)
{
*head = temp;
}
else
{
Node* traversar = *head;
while (traversar->next != nullptr)
traversar = traversar->next;
traversar->next = temp;
}
}
void AddList(Node* ptr1, Node*ptr2, int& carry, Node** new_list)
{
if (ptr1 == nullptr && ptr2 == nullptr)
return;
if (ptr1 != nullptr && ptr2 != nullptr)
AddList(ptr1->next, ptr2->next, carry, &(*new_list));
/* else if (ptr1 != nullptr && ptr2 == nullptr)
AddList(ptr1->next, nullptr, carry, &(*new_list));
else
AddList(nullptr, ptr2->next, carry, &(*new_list));*/
int addition = 0;
if (ptr1 != nullptr && ptr2 != nullptr)
addition = ptr1->data + ptr2->data + carry;
//else if (ptr1 != nullptr && ptr2 == nullptr)
// addition = ptr1->data + carry;
//else
// addition = ptr2->data + carry;
carry = addition > 9 ? 1 : 0;
addition = addition > 9 ? addition % 10: addition;
Node* temp = new Node();
temp->data = addition;
temp->next = nullptr;
temp->next = *new_list;
*new_list = temp;
}
int main()
{
auto printList = [](Node* head) {
Node* temp = head;
while (temp != nullptr) {
std::cout << temp->data;
temp = temp->next;
}
std::cout << std::endl;
};
Node* list1 = nullptr;
Append(&list1, 1);
Append(&list1, 0);
Append(&list1, 0);
printList(list1);
Node* list2 = nullptr;
Append(&list2, 0);
Append(&list2, 9);
Append(&list2, 9);
printList(list2);
std::cout << "========" << std::endl;
Node* new_list = nullptr;
int carry = 0;
AddList(list1, list2, carry, &new_list);
if (carry)
{
Node* temp = new Node();
temp->data = carry;
temp->next = new_list;
new_list = temp;
}
printList(new_list);
return 0;
}