我已经创建了用于构建链表的类。类声明如下:
class LinkedList
{
private:
int data;
LinkedList *next;
static int count;
public:
LinkedList(void);
~LinkedList(void);
int insert(int arg);
int remove(int arg);
bool find(int arg);
};
如何确保此链表的所有节点都被删除?析构函数只负责删除一个节点。以前我也做过这样的链表,但没想过清内存。
最佳答案
天真的实现
~LinkedList() {delete next;}
将做正确的事 - delete
将调用下一个元素的析构函数,这将删除它后面的元素,依此类推,以删除整个列表。
然而,这意味着析构函数被递归调用,因此删除一个很长的列表可能会导致堆栈溢出。迭代可能会更好:
~LinkedList() {
while (LinkedList * head = next) {
next = head->next;
head->next = nullptr;
delete head;
}
}
如评论中所述,将 List
和 Node
类分开可能更合适,List
负责内存管理, Node
是一个包含数据和链接的简单集合。然后析构函数中的错误范围更小,因为它不需要取消任何指针来防止递归:
struct Node {
int data;
Node * next;
};
struct List {
Node * head;
~List() {
while (Node * victim = head) {
head = victim->next;
delete victim;
}
}
};
关于c++ - 如何从内存中取出 'delete' 这个链表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21482700/