编写一个函数来删除单链表中的节点(尾部除外),仅授予对该节点的访问权限
Write a function to delete a node (except the tail) in a singly linked list, given only access to that node
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
void deleteNode(ListNode* node) {
*(node) = *(node->next);
}
我知道这将是结果
节点 = 3 删除节点(节点(
1->2->3
->4->5 1->2->4->5
但是这会导致内存泄漏,指针会指向新节点,但 int 变量 3 是否仍然会在内存中的某个地方浮动?谢谢!
但这会导致内存泄漏吗
是的。
但是 int 变量 3 还会在内存中的某个地方漂浮吗?
不。包含 4 的节点是泄漏的节点,因为它是包含 3 的节点被覆盖,这是指向 4 的节点。结果将是这样的:
4 <--- this is the node which was leaked (since nothing points to it)
->5
/
1->2->4 <--- this is the node that used to contain 3
不可能摆脱节点在slist 中没有指向其前身的指针。
您可以做的是将->data
和->next
从node->next
移动到node
并摆脱node->next
。它将与请求几乎相同 - 删除存储在node->data
中的数据并使列表一个元素更短。
步骤:
- 处置
node->data
- 保存指向要释放的节点的指针
tmp = node->next
- 将下一个节点统计信息复制到当前节点
node->next = tmp->next; node->data = tmp->data
- 处理
tmp
和代码(没有尝试编译(:
node->val = 42; // dispose of node own data (not required for RAII fields)
ListNode* tmp = node->next;
*(node) = *(node->next);
delete tmp;
相关文章:
- 如果我只是不访问queue_front节点的子节点,而是将它们推到队列中呢?还是BFS吗
- 编写一个函数来删除单链表中的节点(尾部除外),仅授予对该节点的访问权限
- 类成员函数无法访问同一类的私有结构节点?
- 在C++中删除双向链表的头节点后出现访问冲突异常
- 使用二进制搜索树中的迭代器对象访问左侧节点
- 尝试从单向链表C++中删除单个节点时出现读取访问冲突
- 有没有办法访问C++ Boost rtree 中的非叶节点
- C++:无法访问节点值
- 如何访问链式哈希表链表中的每个节点
- Lambda 函数,用于调用有权访问类成员的成员函数
- 从链表数组访问节点数据
- 使用访问者设计模式在N- ARY树中重复访问子节点值
- 如何在OMNet++中访问我的模拟的不同节点
- 在节点插件中访问 inspector_agent.h
- 使用QtCreator,如何在我有权访问ssh的远程服务器上构建我的项目?
- 链接列表节点的访问违规:C
- Dijkstra首个节点访问了
- 使用路径调查访问网格中的所有节点
- 如何通过队列指针访问存储在节点中的类中的数据
- 获取从基类指针到具有不同类型的两个派生成员变量的访问权