【问题标题】:recursive destructor for linked list链表的递归析构函数
【发布时间】:2017-06-12 10:20:02
【问题描述】:

我试图搜索该主题,但我发现的所有线程都使用了 while 循环。 但是我想递归地这样做:

template <typename S>
struct node {
    S data;
    node<S> * next; 
};

这是我在链表的析构函数中调用的函数(将头部作为参数传递):

void destroy(node<T> * n) {
    if(n->next != NULL){
        destroy(n->next);
    }
    delete n;
}

不幸的是,结果是分段错误。 有人可以帮我吗?

编辑:完整代码

#include <iostream>

using namespace std;


template <typename T>
class List {
    private:

    template <typename S>
    struct node {
        S data;
        node<S> * next; 
    };

    node<T> * first;

    node<T> * get_last_p() {
        if(first != NULL){
            return get_last(first);
        }
        return NULL;
    }

    node<T> * get_last(node<T> * n) {
        if(n->next != NULL) {
            return get_last(n->next);
        } else {
            return n;
       }
       return NULL;
    }

    void destroy(node<T> * n) {
        if(n->next != NULL){
            destroy(n->next);
        }  
        delete n;
    }


    public:

    List() {first->next = 0;}
    ~List() {destroy(first);}

    void add(T element) {
        node<T> * new_element = new node<T>;
        new_element->data = element;
        if(first == NULL){
            first = new_element;
        } else {
            get_last_p()->next = new_element;
        }
    }

    T get_last() {
        return get_last_p()->data;
    }

    T get_first() {
        return first->data;
    }

};

【问题讨论】:

  • 你确定n 永远不会为空吗?
  • 如果你不知道问题出在哪里,你就不知道问题出在哪里。发布您的代码。
  • 提供重现错误所需的最少代码量。
  • 在构造函数体内:List() {first-&gt;next = 0;} -- first 未初始化。你好 UB!

标签: c++ recursion linked-list destructor


【解决方案1】:

据我所知,在List的构造函数中,first没有被初始化,然后立即被访问。那是未定义的行为。 即使first 以某种不可靠的方式初始化为null,并且first-&gt;next = 0; 不会以某种方式崩溃,你也会在析构函数的destroy 中失败,因为destroy 假定它的原始参数不为null。

我猜你的意思是 List() : first{ new node{} } { first-&gt;next = nullptr; }

如果first 不打算保存一个值,那么您将不得不重构您的代码以首先将first 初始化为null - 没有解决方法 - 并处理first 的情况在您的所有代码中显式地为空。您不能将 first-&gt;next 分配为 null、无效或未定义的指针。

【讨论】:

  • 当我已经在构造函数中初始化 'first' 时,如果 'first' 持有真实值,我如何检查我的 'add' 函数?
  • 已编辑以提供更符合您的意图的解决方案
  • 它适用于您的构造函数。感谢您的帮助!
猜你喜欢
  • 2011-10-21
  • 2016-10-24
  • 2016-03-13
  • 1970-01-01
  • 2021-03-07
  • 2015-07-01
  • 2012-02-03
  • 1970-01-01
  • 2011-03-05
相关资源
最近更新 更多