-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdelete_duplicates.cpp
107 lines (91 loc) · 1.34 KB
/
delete_duplicates.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
//delete duplicates from a sorted linked list
#include <bits/stdc++.h>
using namespace std;
class node{
public:
int data;
node* next;
node(int x)
{
data = x;
next = NULL;
}
};
node* head = NULL;
node* tail = NULL;
//this function removes duplicates from a sorted array
void delete_duplicates()
{
node *temp = head;
node *p = head;
while(p != NULL && p->next != NULL)
{
if(p->data == p->next->data)
{
temp = p->next;
p->next = p->next->next;
delete temp;
continue;
}
p = p->next;
}
}
//this function removes duplicats from a unsorted array
void delete_duplicates_unsorted()
{
if(head == NULL || head->next == NULL)
{
return;
}
node *current = head;
node *prev = NULL;
unordered_set<int> s;
while(current != NULL)
{
int x = current->data;
if(s.find(x) != s.end())
{
prev->next = current->next;
delete current;
}
else
{
s.insert(x);
prev = current;
}
current = prev->next;
}
}
void insert(int x){
node *temp = new node(x);
if(head == NULL)
{
head = temp;
tail = temp;
}
tail->next = temp;
tail = temp;
}
void display(node *p)
{
while(p != NULL)
{
cout << p->data << " ";
p = p->next;
}
cout << "\n";
}
int main()
{
int n,x;
cout << "Enter n: ";
cin >> n;
for(int i = 0; i < n; i++)
{
cin >> x;
insert(x);
}
delete_duplicates();
display(head);
return 0;
}