考虑一个已实现的 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 assignedp=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/