- Joined
- Nov 4, 2023
- Messages
- 1
- Reaction score
- 0
In the code given below, after the execution of whole program and displaying the circular linked list the program is going in infinite loop can you please spot the error? The code perfectly displays everything and when i remove the destructor there is no infinite loop program stops with perfect output
C++:
#include <iostream>
using namespace std;
class Node
{
public:
int data;
Node *next;
Node(int data)
{
this->data = data;
next = NULL;
}
};
class c_list
{
private:
Node *head,*last;
public:
c_list()
{
head = NULL;
last = head;
}
~c_list() //destructor to free memory
{
Node* temp = head,*next;
while(temp!=NULL)
{
next = temp->next;
delete temp;
temp = next;
}
}
void insert_e(int);
void Display();
};
void c_list :: insert_e(int data)
{
Node *p;
p = new Node(data);
if(head==NULL)
{
head = p;
p->next = head;
last = p;
}
else
{
p->next = last->next ;
last->next = p;
last = p;
}
}
void c_list :: Display()
{
Node *temp=head;
cout<<"Circular linked list : Head -> ";
do
{
cout<<temp->data<<" -> ";
temp = temp -> next;
}while(temp!= head);
cout<<"Head "<<endl;
}
int main()
{
c_list c;
int A[]={2,4,6,8};
for(int i=0;i<4;i++)
c.insert_e(A);
c.Display();
return 0;
}
Last edited: