Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete a linked list without recursion?

I'm trying to find a way of deleting a linked list without recursion, because a stack overflow isn't really something nice.

I have a struct as follows:

typedef struct _my_Item
{
     _my_Item(const std::string& name)
     {
          m_name = name;
     }
     ~my_Item()
     {
          delete next; // this recursively deletes the "tail" of the list
          next = NULL;
     }
     struct _my_Item *next;
     std::string m_name;
     // ... More members here...
}

In some piece of code (not relevant here) I'm constructing a list from a data file using the above structure. I keep the pointer to the head of the list in a variable and can work with it. All fine. When I finally call the destructor on the head of the list, the destructor gets called and the delete next; causes a recursion to delete the "tail" of the list (which is the entire list without the first element). Now since the list is quite long, I see a stack overflow sometimes.

Is there a nice way to get around this problem?

like image 630
PMF Avatar asked Feb 22 '26 23:02

PMF


1 Answers

~my_Item()
{
    while (next)
    {
       _my_Item* item = next;
       next = item->next;
       item->next = NULL; // this prevents the recursion
       delete item;
    }
}
like image 174
selbie Avatar answered Feb 24 '26 13:02

selbie