链表的析构函数 [英] Destructor for a linked List

查看:320
本文介绍了链表的析构函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个linked_list,目前我的析构器不能正常工作。不完全确定为什么。可以有人解释我如何解决这个。
class linked_list {
private:

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;

这是我的析构函数

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


推荐答案

问题在这里:

delete first;
first = first->next;

当您先删除 访问 first->下一页。将 first-> next 缓存到节点* 类型的临时变量中,然后执行 delete首先修复此问题:

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

这篇关于链表的析构函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆