c++ - 删除正向链表

标签 c++ linked-list forward-list

有两种已知的方式(只有两种?)删除正向链表

  1. 一种方法是递归函数,它效率低下,如果列表太大会导致堆栈溢出

  2. 另一种方式(高效的方式)是像这样迭代和删除节点的函数:

    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/

相关文章:

c++ - 无法推断编译器目标三元组

c++ - 使用 clang 和 libstdc++ 时无法使用实验性::可选的常量引用

c++ - 使用 gettimeofday 和 localtime 的准确时间戳

c++ - std::list::splice() 和 std::forward_list::splice_after() 在 C++11 中声明为 noexcept 吗?

c++ - 如何检测异常何时发生?

pointers - this指针-C++链表

c - 链接列表 : Dequeue correctly returns popped data, 但尝试使用打印时出现段错误

java - 实现链表的快速排序?

c++ - std::forward_list::insert_after 线程安全