-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathad_2_nos.cpp
94 lines (80 loc) · 1.6 KB
/
ad_2_nos.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
#include <iostream>
struct Node{
int data;
Node* next;
};
class LinkedList{
private:
Node* head;
public:
LinkedList(){
head = NULL;
}
void insert(int x) {
Node* newNode = new Node;
if (newNode == NULL) {
std::cout << "Memory issue";
return;
}
newNode->data = x;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
}
else {
Node* temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
void display(){
Node* temp = head;
while(temp){
std::cout << temp->data << '\t';
temp = temp->next;
}
}
Node* getHead(){
return head;
}
};
void addTwoNumbers(Node* l1, Node* l2){
LinkedList l3;
int carry = 0;
while(l1 && l2){
int sum = l1->data + l2->data + carry;
if(sum > 9){
carry = 1;
l3.insert(sum % 10);
}
else{
carry = 0;
l3.insert(sum);
}
if(l1 == NULL){
l3->next = l2;
}
else if(l2 == NULL){
l3->next = l1;
}
else{
l1 = l1->next;
l2 = l2->next;
}
}
l3.display();
}
int main(){
LinkedList l1;
LinkedList l2;
l1.insert(2);
l1.insert(4);
l1.insert(3);
l2.insert(5);
l2.insert(6);
l2.insert(4);
addTwoNumbers(l1.getHead(), l2.getHead());
return 0;
}