Remove all occurences of duplicates in a linked list || GFG POTD today || 3 july
ฝัง
- เผยแพร่เมื่อ 2 ก.ค. 2024
- time complexity - [O(n) we are iterating through the linked list once to create the map of occurrences and then iterating through the map to create a new linked list with unique elements.]
space complexity -[ O(n) we are using a map to store the occurrences of each element in the linked list ]
.
.
**check comments for code 😀
.
.
.
#gfg #gfgstreak #gfgpotd #potd #easy #programming #coding #dailychallenge #dailycoding #geeksforgeeks #easyapproach #gfgpotdtoday
class Solution {
public:
Node* removeAllDuplicates(struct Node* head) {
mapmp;
Node *temp=head;
//create a map to store the occurence of the data of linked list
while(temp!=NULL){
mp[temp->data]++;
temp=temp->next;
}
Node *newHead=NULL; //to point at the head of new linked list
//iterate through tha map and check for the elements having freq as 1
for(auto i:mp){
if(i.second==1){
if(newHead==NULL){ //to check whether my newhead is pointing towards any node
Node *newNode=new Node(i.first);
newHead=newNode;
head=newNode;
}
else{
Node *newNode=new Node(i.first);
head->next=newNode;
head=newNode;
}
}
}
return newHead;
}
};