Destructor for a linked List

2020-08-04 09:29发布

问题:

I have a linked_list and currently my destructor is not working properly. Not entirely sure why. Can somebody explain me how to solve this?

class linked_list {
 private:

struct node
{
    // String in this node
    std::string data;

    // Pointer to next node
    struct node *next;
};

//First item in the list
struct node *first;

Here is my destructor

linked_list::~linked_list(void)
{
while (first)
{
    delete first;
    first = first->next;
}
}

回答1:

The problem lies here:

delete first;
first = first->next;

When you delete first, but then try to access first->next. Cache first->next into a temp variable of type node*, then do delete first to fix this:

struct node* temp;
while (first != NULL)
{
    temp = first->next;
    delete first;
    first = temp;
}


回答2:

change to

 linked_list::~linked_list(void)
{
struct node *next;
while (first != NULL)
{
    next = first->next;
    delete first;
    first = next;
}
 }


回答3:

When you 'delete' first, you actually clear all the links from it. Now, if you try to access some other node using this, will not produce the required result.

First, you have to point that node with some other pointer, so that you still have some link which you can access later.