Search code examples
c++linked-listdestructordoubly-linked-list

Linked list destructor not working


I've written a destructor for a doubly linked list which is not working properly. There's a loop to delete the values. The line-of-control comes out of the that loop but the program doesn't finish. I mean, the main does not end.

Never mind, I figured it out.


Solution

  • You can write the destructor cimpler. For example

    LinkedList::~LinkedList() 
    {
        for ( ListItem *node = head; node; ) 
        {
            ListItem *temp = node;
            node = node->next;
            delete temp;
        }
    
        head = nullptr;
    }
    

    Or

    LinkedList::~LinkedList() 
    {
        while ( head ) 
        {
            ListItem *temp = head;
            head = head->next;
            delete temp;
        }
    
        head = nullptr;
    }