-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlec5_7.cpp
159 lines (132 loc) Β· 3.09 KB
/
lec5_7.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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
//{ Driver Code Starts
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
/* Linked list Node */
struct Node {
int data;
struct Node* next;
Node(int x) {
data = x;
next = NULL;
}
};
Node* buildList() {
vector<int> arr;
string input;
getline(cin, input);
stringstream ss(input);
int number;
while (ss >> number) {
arr.push_back(number);
}
if (arr.empty()) {
return NULL;
}
int val = arr[0];
int size = arr.size();
Node* head = new Node(val);
Node* tail = head;
for (int i = 1; i < size; i++) {
val = arr[i];
tail->next = new Node(val);
tail = tail->next;
}
return head;
}
void printList(Node* n) {
while (n) {
cout << n->data << " ";
n = n->next;
}
cout << endl;
}
// } Driver Code Ends
/* node for linked list:
struct Node {
int data;
struct Node* next;
Node(int x) {
data = x;
next = NULL;
}
};
*/
class Solution {
public:
Node* Reverse(Node *curr , Node *prev)
{
if(curr == NULL)
{
return prev;
}
Node *front = curr->next;
curr->next = prev;
return Reverse(front , curr);
}
// Function to add two numbers represented by linked list.
Node* addTwoLists(struct Node* first, struct Node* second) {
// code here
first = Reverse(first , NULL);
second = Reverse(second , NULL);
Node *curr1 = first , *curr2 = second;
Node *head = new Node(0);
Node *tail = head;
//Addition
int sum , carry = 0 ;
while(curr1 && curr2)
{
sum = curr1->data+ curr2->data +carry;
tail->next = new Node(sum%10);
curr1 = curr1->next;
curr2 = curr2->next;
tail = tail->next;
carry = sum/10;
}
// sum add karna padega
while(curr1)
{
sum = curr1->data+carry;
tail->next = new Node(sum%10);
curr1 = curr1->next;
tail = tail->next;
carry = sum/10;
}
// curr2 exist toh nahi karta
while(curr2)
{
sum = curr2->data+carry;
tail->next = new Node(sum%10);
curr2 = curr2->next;
tail = tail->next;
carry = sum/10;
}
// carry
while(carry)
{
tail->next = new Node(carry%10);
tail = tail->next;
carry/=10;
}
//Dummy node bhi present
head = Reverse(head->next , NULL);
return head;
}
};
//{ Driver Code Starts.
int main() {
int t;
cin >> t;
cin.ignore(); // To ignore the newline character after the integer input
while (t--) {
Node* num1 = buildList();
Node* num2 = buildList();
Solution ob;
Node* res = ob.addTwoLists(num1, num2);
printList(res);
}
return 0;
}
// } Driver Code Ends