c++ - 使用引用指向节点的指针的函数删除链表中的节点?

标签 c++ pointers linked-list reference nodes

考虑一个已实现的 struct Node :

template <class T>
struct Node {
    Node<T> * next;
    T data;
    // Other functions for adding nodes etc...
};

然后一个函数remove(...)给出,它采用参数 1) 引用指向节点 的指针p和 2) 数据 d即将被删除:
template <class T>
void remove(Node<T> *& p, T d) {
    if (p != nullptr) {
        if (p->data == d) {
            Node<T> * temp = p;
            p = p->next;
            delete temp;
            remove(p, d);
        }
        else {
            remove(p->next, d);
        };
    };
};

问题

我不太明白这将如何工作。由于temp指向 p , 不会分配 p=p->next无论如何都要在 delete temp 中删除,使此功能失败?有什么我想念的吗?也许与指针 p 有关作为引用传递?

谢谢你。

最佳答案

Since temp points to p, won't the assigned p=p->next be removed anyhow in delete temp, making this function fail?


temp不指向 p但是对于什么p点。请注意,指针是具有收件人作为值的变量,并且当 rhs 上的指针返回其值时。

和作业p = p -> next使 p 的值是 p 之后节点的地址(即)p -> next 返回的地址

关于c++ - 使用引用指向节点的指针的函数删除链表中的节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61849443/

相关文章:

c++ - Simulink "Access Violation"写入 C++ lambda 函数捕获列表中的 PWork 变量

c++ - 高速有效地更新 QTableView

c++ - C++ 中的 key_compare 与 key_comp

c - C中的数组是通过指针使用的吗?

c - 数组和函数指针

C++链表isEmpty函数

c++ - 在 C++ 中的 OpenCV 中旋转图像而不进行裁剪

c++ - 另一个类的类指针数组的类指针数组的段错误

java - 为什么java链表实现使用接口(interface)deque?

java - 相同的变量名使用了两次但程序没有抛出错误?