Here, I have written a code to implement a singly linked list in C++. Then I have made a function to remove duplicates from the list if any. My program is working perfectly but when I call remove duplicate function its not working , not giving any results. I have tried solving it for more than 10hrs. I think the problem is on delete function but I don't know how to solve it.
#include<bits/stdc++.h>
using namespace std;
class node{
public:
int data;
node *next;
node(int d)
{
this->data=d;
this->next=nullptr;
}
};
class ll
{
private:
node *head=nullptr;
node *tail=nullptr;
public:
void inserthead(int value)
{
node *newnode=new node(value);
if(head==nullptr)
{
head=newnode;
tail=newnode;
}
else{
newnode->next=head;
head=newnode;
}
}
void inserttail(int value)
{
node *newnode=new node(value);
if(tail==nullptr)
{
head=newnode;
tail=newnode;
}
else{
tail->next=newnode;
tail=newnode;
}
}
void print()
{
node *temp=head;
while(temp!=nullptr)
{
cout<<endl<<temp->data<<endl;
temp=temp->next;
}
}
void deletenode(int value)
{
node *currnode=head;
int c=0;
while(currnode!=nullptr)
{
if(currnode->data==value)
{
break;
}
currnode=currnode->next;
c++;
}
if(c==0)
{
head=head->next;
delete currnode;
}
else if(c!=0 && currnode->next!=nullptr)
{
node *temp1=head;
int ct=0;
while(ct<c-1)
{
temp1=temp1->next;
ct++;
}
ct=0;
node *temp2=head;
while(ct<c+1)
{
temp2=temp2->next;
ct++;
}
temp1->next=temp2;
delete currnode;
}
else
{
node *temp=head;
int ct=0;
while(ct<c-1)
{
temp=temp->next;
ct++;
}
temp->next=nullptr;
tail=temp;
delete currnode;
}
}
void removeduplicates()
{
node *curr=head;
while(curr!=nullptr)
{
node *compare=curr->next;
while(compare!=nullptr)
{
if(compare->data==curr->data)
{
deletenode(compare->data);
}
compare=compare->next;
}
curr=curr->next;
}
}
};
int main()
{
ll l1;
l1.inserthead(10);
l1.inserthead(10);
l1.inserttail(9);
l1.inserttail(8);
l1.inserttail(11);
l1.removeduplicates();
l1.print();
return 0;
}