forked from Ishj21/cpp-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmerge2sortedarr.cpp
More file actions
106 lines (83 loc) · 1.83 KB
/
merge2sortedarr.cpp
File metadata and controls
106 lines (83 loc) · 1.83 KB
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
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
Node *next;
};
Node *getNode(int data)
{
Node *temp = (Node *)malloc(sizeof(Node));
temp->data = data;
temp->next = NULL;
return temp;
}
Node *sortedMerge(struct Node *a, struct Node *b)
{
Node *result = NULL;
if (a == NULL)
return (b);
else if (b == NULL)
return (a);
if (a->data <= b->data)
{
result = a;
result->next = sortedMerge(a->next, b);
}
else
{
result = b;
result->next = sortedMerge(a, b->next);
}
return (result);
}
void removeDupli(Node *head)
{
Node *current = head;
Node *next_next;
if (current == NULL)
return;
while (current->next != NULL)
{
if (current->data == current->next->data)
{
next_next = current->next->next;
free(current->next);
current->next = next_next;
}
else
{
current = current->next;
}
}
}
Node *sortedMergeWithoutDuplicate(Node *head1, Node *head2)
{
Node *head = sortedMerge(head1, head2);
removeDupli(head);
return head;
}
//insert printlist here
int main()
{
Node *head1 = getNode(1);
head1->next = getNode(2);
head1->next->next = getNode(5);
head1->next->next->next = getNode(6);
head1->next->next->next->next = getNode(11);
Node *head2 = getNode(2);
head2->next = getNode(3);
head2->next->next = getNode(6);
head2->next->next->next = getNode(12);
Node *head3;
head3 = sortedMergeWithoutDuplicate(head1, head2);
cout << "List 1: " << endl;
printList(head1);
cout << endl
<< "List 2: " << endl;
printList(head2);
cout << endl
<< "Merged List without Duplicates : " << endl;
printList(head3);
return 0;
}