-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Remove_all_Duplicates_from_Linkedlist.cpp
85 lines (78 loc) · 1.48 KB
/
Remove_all_Duplicates_from_Linkedlist.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
/*
Given the Sorted Linked list head which contain duplicates, the task is
to delete all the duplicate and make linked list such that every element
appear just one time.
Example:
Original Linked list : 1 1 2 2 3
Answer : 1 2 3
*/
#include <bits/stdc++.h>
using namespace std;
class Node
{
public:
int data;
Node *next;
};
void push(Node **head, int n_data)
{
Node *newdata = new Node();
newdata->data = n_data;
newdata->next = (*head);
(*head) = newdata;
}
void printlinkedlist(Node *temp)
{
while (temp != NULL)
{
cout << "->" << temp->data;
temp = temp->next;
}
}
Node *delete_duplicates(Node *head)
{
Node *curr = head;
while (curr && curr->next)
{
if (curr->next->data == curr->data)
{
curr->next = curr->next->next;
}
else
{
curr = curr->next;
}
}
return head;
}
int main()
{
Node *head = NULL;
int n;
cout << "Enter number of Elements:";
cin >> n;
cout << "Enter elements:";
for (int i = 0; i < n; i++)
{
int a;
cin >> a;
push(&head, a);
}
cout << "Original Linked list:\n";
printlinkedlist(head);
cout << "\nNew Linked List:\n";
head = delete_duplicates(head);
printlinkedlist(head);
}
/*
Sample Input:
Enter number of Elements:5
Enter elements:1 1 2 2 3
Sample Output:
Original Linked list:
->3->2->2->1->1
New Linked List:
->3->2->1
Time-Complexity: O(n)
Space-Complexity: O(1)
*/