-
Notifications
You must be signed in to change notification settings - Fork 5
/
Add_two_numbers_represented_as_linklist.cpp
107 lines (95 loc) · 2.13 KB
/
Add_two_numbers_represented_as_linklist.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
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
struct Node {
int data;
struct Node* next;
Node(int x) {
data = x;
next = NULL;
}
};
struct Node* addTwoLists(struct Node* first, struct Node* second);
Node* addTwoLists(Node* first, Node* second) {
Node* f=first;
Node* s=second;
Node* sum =(struct Node*)malloc(sizeof(struct Node*));
sum->data=-1;
Node* temp=sum;
int carry=0;
int add=0;
while(f!=NULL || s!=NULL){
int x=0;
if(f!=NULL){
x=x+f->data;
f=f->next;
}
if(s!=NULL){
x=x+s->data;
s=s->next;
}
x=x+carry;
add=x%10;
carry=x/10;
Node* e =(struct Node*)malloc(sizeof(struct Node*));
e->data=add;
sum->next=e;
sum=e;
}
if(carry==0){
sum->next=NULL;
}
else{
Node* e =(struct Node*)malloc(sizeof(struct Node*));
e->data=carry;
sum->next=e;
sum=e;
sum->next=NULL;
}
return temp->next;
}
void push(struct Node** head_ref, int new_data) {
struct Node* new_Node = new Node(new_data);
new_Node->next = (*head_ref);
(*head_ref) = new_Node;
}
void printList(struct Node* Node) {
while (Node != NULL) {
printf("%d ", Node->data);
Node = Node->next;
}
printf("\n");
}
void freeList(struct Node* Node) {
struct Node* temp;
while (Node != NULL) {
temp = Node;
Node = Node->next;
free(temp);
}
}
int main(void) {
int t, n, m, i, x;
cin >> t;
while (t--) {
struct Node* res = NULL;
struct Node* first = NULL;
struct Node* second = NULL;
cin >> n;
for (i = 0; i < n; i++) {
cin >> x;
push(&first, x);
}
cin >> m;
for (i = 0; i < m; i++) {
cin >> x;
push(&second, x);
}
res = addTwoLists(first, second);
printList(res);
if (first) freeList(first);
if (second) freeList(second);
}
return 0;
}