【发布时间】: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->next = 0;}--first未初始化。你好 UB!
标签: c++ recursion linked-list destructor