使用函数引用指向节点的指针删除链表中的节点?
Remove node in linked list with function taking reference to pointer to a node?
考虑一个实现的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
作为引用传递有关?
谢谢。
由于临时指向
p
,分配的p=p->next
不会被删除 无论如何,在删除临时,使此功能失败?
temp
不是指向p
,而是指向p
要点。请注意,指针是将收件人作为值的变量,当 rhs 上的指针返回其值时。
赋值p = p -> next
使p
的值成为节点在p
之后的地址(即p -> next
返回的地址
相关文章:
- 为什么我的删除节点函数实际上没有删除节点?
- 我们可以删除链表中静态内存中的节点吗
- 为什么"delete"关键字不删除节点?
- 为什么我的双向链表删除函数会删除多个节点?
- 编写一个函数来删除单链表中的节点(尾部除外),仅授予对该节点的访问权限
- 删除 XML 文件中的子节点C++
- 创建了一个链表,但如何删除 c++ 中的"所有"节点
- 从unordered_map中删除单个节点
- 删除链表中的特定节点
- 在C++中删除双向链表的头节点后出现访问冲突异常
- 删除链表中的节点 - 分段错误
- 删除链接列表中剩余的最后一个节点
- 避免在使用链接列表从 deque 中删除最后一个节点时出现内存泄漏
- 使用函数引用指向节点的指针删除链表中的节点?
- 双向链表 - 无法删除第一个节点
- 双向链表 std::unique_ptr 类在节点删除时无法按预期工作
- BST 节点删除 - 指针未正确删除
- 节点删除功能的链表问题
- 布尔函数始终为真,单向链表中的尾节点删除创建无限循环
- AVL树中节点删除值异常