有两种已知的方式(只有两个?),删除前链表删除前链表
一种方法是递归函数效率低且会给堆栈溢出如果列表太大
的另一种方式(有效)是迭代并删除节点这样的功能:
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...
};
我测试,它工作得很好......我觉得这种方式更清洁,但不知道是否会有副作用吗?
如果您只想删除一个节点,该怎么办? – PaulMcKenzie
@PaulMcKenzie:首先从列表中取消链接,它将'node-> next'设置为'nullptr',使'delete this-> next'成为无操作。 – MSalters