forked from imsushant12/GFG-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Remove_duplicates_from_an_unsorted_linked_list.cpp
89 lines (78 loc) · 2.15 KB
/
Remove_duplicates_from_an_unsorted_linked_list.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
/*
Problem Statement:
-----------------
Given an unsorted linked list of N nodes. The task is to remove duplicate elements from this unsorted Linked List.
When a value appears in multiple nodes, the node which appeared first should be kept, all others duplicates are to be removed.
Example 1:
---------
Input:
N = 4
value[] = {5,2,2,4}
Output: 5 2 4
Explanation:Given linked list elements are
5->2->2->4, in which 2 is repeated only.
So, we will delete the extra repeated
elements 2 from the linked list and the
resultant linked list will contain 5->2->4
Example 2:
---------
Input:
N = 5
value[] = {2,2,2,2,2}
Output: 2
Explanation:Given linked list elements are
2->2->2->2->2, in which 2 is repeated. So,
we will delete the extra repeated elements
2 from the linked list and the resultant
linked list will contain only 2.
Your Task: You have to complete the method removeDuplicates() which takes 1 argument: the head of the linked list.
Your function should return a pointer to a linked list with no duplicate element.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N)
*/
// Link --> https://practice.geeksforgeeks.org/problems/remove-duplicates-from-an-unsorted-linked-list/1#
// Code:
class Solution
{
public:
Node* removeDuplicates(Node *head)
{
if(head == NULL)
return NULL;
Node *newHead = head;
unordered_set <int> uns;
uns.insert(head->data);
while(newHead->next != NULL)
{
if(uns.find(newHead->next->data) != uns.end())
{
newHead->next = newHead->next->next;
}
else
{
uns.insert(newHead->next->data);
newHead = newHead->next;
}
}
return head;
}
};
/*
// Other way (using previous and current-node pointer):
Node *removeDuplicates(Node *head)
{
Node *newHead = head;
while(newHead->next != NULL)
{
if(newHead->data == newHead->next->data)
{
newHead->next = newHead->next->next;
}
else
{
newHead = newHead->next;
}
}
return head;
}
*/