I tried dry running this problem and still can’t find any error from 2 days
Problem link:
Code
Node * removeDuplicates( Node *head)
{
// your code goes here
map<int,int> mp;
Node* temp=head;
while(temp->next!=head)
{
mp[temp->data]++;
temp=temp->next;
}
temp=head->next;
Node* prev=head;
Node* nextNode;
while(temp->next!=NULL)
{
nextNode=temp->next;
if(mp[temp->data]>1)
{
prev->next= nextNode;
delete(temp);
temp=nextNode;
}
else{
temp=temp->next;
prev=prev->next;
}
}
return head;
}
My Code. I think this will help you.
Node * removeDuplicates( Node *head)
{
// your code goes here
Node *curr = head;
Node *temp = NULL;
unordered_set<int> st;
while(curr != NULL)
{
if(st.find(curr->data) != st.end())
{
temp->next = curr->next;
curr = curr->next;
// delete(temp);
}
else{
st.insert(curr->data);
temp = curr;
curr = curr->next;
}
}
return head;
}
I think the error in this line temp->next!=head, it should be temp->next!=NULL
(in first while loop)
first sort the linked list
then try this
public class duplicate{
//code for sorting the linked List///
public static Node sorting(Node head){
Node current = null
Node current2 = null
current = head;
while(current!=null){
current2=current.next;
while(current2!=null){
if(current.data>current2.data){
int temp = current.data;
current.data = current2.data;
current2.data = temp;
}
current2= current2.next;
}
current = current.next;
}
return head;
}
public static Node removeduplicate(Node head){
Node head1 = sorting(head);
Node p = null;
Node current = head1;
while(current!=null && current.next!=null){
if(current.data==current.next.data){
p = current.next.next;
if(p==null){
current.next=null;
break;
}
current.next=p;
}
if(current.data!=current.next.data){
current = current.next;
}
}
return head1;
}
}
thanks for pointing it out.
But it is still giving segmentation fault(Although,it is passing for sample test cases)