Skip to content

Commit 55163b1

Browse files
committed
Remove all Duplicates from Linkedlist added
1 parent 9b1f10c commit 55163b1

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
/*
2+
Given the Sorted Linked list head which contain duplicates, the task is
3+
to delete all the duplicate and make linked list such that every element
4+
appear just one time.
5+
Example:
6+
Original Linked list : 1 1 2 2 3
7+
Answer : 1 2 3
8+
*/
9+
10+
#include <bits/stdc++.h>
11+
using namespace std;
12+
13+
class Node
14+
{
15+
public:
16+
int data;
17+
Node *next;
18+
};
19+
void push(Node **head, int n_data)
20+
{
21+
Node *newdata = new Node();
22+
newdata->data = n_data;
23+
newdata->next = (*head);
24+
(*head) = newdata;
25+
}
26+
void printlinkedlist(Node *temp)
27+
{
28+
while (temp != NULL)
29+
{
30+
cout << "->" << temp->data;
31+
temp = temp->next;
32+
}
33+
}
34+
Node *delete_duplicates(Node *head)
35+
{
36+
Node *curr = head;
37+
while (curr && curr->next)
38+
{
39+
if (curr->next->data == curr->data)
40+
{
41+
curr->next = curr->next->next;
42+
}
43+
else
44+
{
45+
curr = curr->next;
46+
}
47+
}
48+
return head;
49+
}
50+
int main()
51+
{
52+
Node *head = NULL;
53+
int n;
54+
cout << "Enter number of Elements:";
55+
cin >> n;
56+
cout << "Enter elements:";
57+
for (int i = 0; i < n; i++)
58+
{
59+
int a;
60+
cin >> a;
61+
push(&head, a);
62+
}
63+
cout <<"Original Linked list:\n";
64+
printlinkedlist(head);
65+
cout <<"\nNew Linked List:\n";
66+
head = delete_duplicates(head);
67+
printlinkedlist(head);
68+
}
69+
70+
/*
71+
Sample Input:
72+
Enter number of Elements:5
73+
Enter elements:1 1 2 2 3
74+
75+
Sample Output:
76+
Original Linked list:
77+
->3->2->2->1->1
78+
New Linked List:
79+
->3->2->1
80+
81+
Time-Complexity: O(n)
82+
Space-Complexity: O(1)
83+
*/

0 commit comments

Comments
 (0)