-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmerge.cpp
102 lines (97 loc) · 1.83 KB
/
merge.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
#include<iostream>
#include<cstdlib>
using namespace std;
typedef struct node
{
int data;
struct node *next;
}node;
int count;
void create(node ** head,int n)
{
node *temp;
if(*head == NULL) {
temp = (node *)malloc(sizeof(node));
temp->data = n;
*head = temp;
(*head)->next = NULL;
//cout << "temp data is " << temp->data << endl;
}else {
create((&(*head)->next),n);
}
}
void print(node *head)
{
while(head != NULL) {
cout << (head)->data << "-->";
(head) = (head)->next;
}
cout << endl;
}
node * call(void)
{
node *head = NULL;
while(1) {
int n;
cin >> n;
if(n == 999) {
break;
}else {
count++;
create(&head,n);
}
}
print(head);
//cout << "starting node is " << head->data << endl;
return(head);
}
node * merge(node **head,node **head1)
{
node *temp = NULL;
while((*head) != NULL && (*head1) != NULL) {
if((*head)->data == (*head1)->data) {
create(&temp,(*head)->data);
(*head) = (*head)->next;
(*head1) = (*head1)->next;
}else {
if((*head)->data < (*head1)->data) {
//cout << "first-one\n";
create(&temp,(*head)->data);
(*head) = (*head)->next;
}else if((*head)->data > (*head1)->data){
//cout << "second-one\n";
create(&temp,(*head1)->data);
(*head1) = (*head1)->next;
}
}
}
if(*head != NULL) {
while(*head != NULL) {
create(&temp,(*head)->data);
(*head) = (*head)->next;
}
}
if(*head1 != NULL) {
while(*head1 != NULL) {
create(&temp,(*head1)->data);
(*head1) = (*head1)->next;
}
}
return(temp);
}
int main()
{
node *head,*head1;
node *current;
//count = 0;
cout << "enter the first list\n";
head = call();
//cout << "no. of nodes are " << count << endl;
count = 0;
cout << "enter the second list\n";
head1 = call();
//cout << "no. of nodes are " << count << endl;
current = merge(&head,&head1);
print(current);
return 0;
}