编写一个函数来删除单链表中的节点(尾部除外),仅授予对该节点的访问权限

Write a function to delete a node (except the tail) in a singly linked list, given only access to that node

本文关键字:节点 访问权 权限 访问 尾部 一个 函数 链表 单链表 删除      更新时间:2023-10-16
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->nextnode->next移动到node并摆脱node->next。它将与请求几乎相同 - 删除存储在node->data中的数据并使列表一个元素更短。

步骤:

  1. 处置node->data
  2. 保存指向要释放的节点的指针tmp = node->next
  3. 将下一个节点统计信息复制到当前节点node->next = tmp->next; node->data = tmp->data
  4. 处理tmp

和代码(没有尝试编译(:

node->val = 42; // dispose of node own data (not required for RAII fields)
ListNode* tmp = node->next;
*(node) = *(node->next);
delete tmp;