c++linked-listforward-list

Deleting forward linked list


There are two known ways (only two ?) to delete forward linked list

  1. One way is the recursive function which is inefficient and would give stack overflow if the list is too large

  2. Another way (the efficient) is a function that iterates and deletes nodes like this:

    class Forward_list {
    public:
       // Constructor...
    
       ~Forward_list() { if(head) destroy(); }
    
       void destroy() {
            node* prev = nullptr;
            while (head) {
                prev = head;
                head = head->next;
                delete prev;
            }
        }
    
        // functions...
    private:
        // data members...
        node* head;
    };
    

Now what about doing it this way:

class Forward_list {
public:
    // Constructor...

    ~Forward_list() { if(head) delete this->head; }

    // functions...
private:
    struct node {
        ~node() { delete this->next; } // <- this way
        type data;
        node* next;
    };
    node* head;
    // data members...
};

I tested it and it works fine ... I find this way cleaner but not sure if there would be side effects ?


Solution

  • Your solution is technically correct, the only problem I can think of is you can't delete one node without deleting all the nodes that follow.