Infinite loop problem

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:
Joined
Sep 3, 2023
Messages
36
Reaction score
2
Add this into the destructor to break the circular link.
if( last != NULL ) last->next = NULL;

Also in the insert function, its pointless to setting the next to a NULL value. So like this is better.
if( head == NULL ) head = last = p;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top