有两种已知的方式(只有两种?)删除正向链表
一种方法是递归函数,它效率低下,如果列表太大会导致堆栈溢出
另一种方式(高效的方式)是像这样迭代和删除节点的函数:
class Forward_list { public: // Constructor... ~Forward_list() { if(head) destroy(); } void destroy() { node* prev = nullptr; while (head) { prev = head; head = head->next; delete prev; } } // functions... private: // data members... node* head; };
现在如何这样做:
class Forward_list {
public:
// Constructor...
~Forward_list() { if(head) delete this->head; }
// functions...
private:
struct node {
~node() { delete this->next; } // <- this way
type data;
node* next;
};
node* head;
// data members...
};
我测试了它,它工作正常......我发现这种方式更干净,但不确定是否会有副作用?
最佳答案
你的解决方案在技术上是正确的,我能想到的唯一问题是你不能删除一个节点而不删除后面的所有节点。
关于c++ - 删除正向链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37513425/