Destructor for a linked List

萝らか妹 提交于 2019-12-22 01:03:31

问题


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;
}
 }


来源:https://stackoverflow.com/questions/15672812/destructor-for-a-linked-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!