In the following code when i try to display the list after removing the first element, its resulting in endless loop of next elements. This problem doesn’t occur when other than first element is removed. I have no clue why is this happening? Can someone please tell me where is the mistake?
#include<iostream>
using namespace std;
class node
{
public:
int data;
node *link;
};
class linkedlist
{ node *head;
public:
linkedlist()
{
head=NULL;
}
int add(int data1)
{ node *insertnode=new node;
insertnode->data=data1;
insertnode->link=NULL;
node *temp=head;
if(temp!=NULL)
{
while(temp->link!=NULL)
{
temp=temp->link;
}
temp->link=insertnode;
}
else{head=insertnode;}
}
void disp()
{ node *temp1=head;
cout<<endl;
if(temp1==NULL)
{cout<<"Empty"<<endl;
}
if(temp1->link==NULL)
{
cout<<temp1->data<<endl;
}
else{
do{cout<<temp1->data<<endl;
temp1=temp1->link;
}
while(temp1!=NULL);
}
}
int remove(int removedata)
{
node *temp2=head;
if(temp2==NULL)
{}
if(temp2->link==NULL)
{
delete temp2;
head=NULL;
}
else
{
node *previous;
do
{
if(temp2->data==removedata) break;
previous=temp2;
temp2=temp2->link;
}while(temp2!=NULL);
previous->link=temp2->link;
delete temp2;
}
}
};
int main()
{
linkedlist list;
list.add(10);
list.add(100);
list.add(200);
list.remove(10);
list.disp();
}
Thank you all. The problem has been solved
Have a look on your deletion:
If the first element is the matched one, the loop will immidaiately terminate, resulting in uninitializing
previous, and not changingtemp2(it is still the head).What you will now do is:
previous->linkto some value. Note that this is undefined behavior, since you have no idea whatpreviousis.temp2– which is the head element, but never changing the head. This will result that the first element in the list is undefined, and once accessing it anything can happen (again, undefined behavior).So, basically – after you delete the first element – when you try to display the list, anything can happen – including the infinite loop you are encountering.