用于删除链接列表的节点的伪代码

Pseudocode for removing a node of a linked list

本文关键字:节点 伪代码 列表 删除 链接 用于      更新时间:2023-10-16

假设p是指向链表中某个节点的指针,*p不是尾节点。删除*p之后的节点的步骤是什么?每一步使用一个英语短句。

我的想法是:1) 创建一个class node类型的临时变量,并在临时变量旁边分配p->——将此变量称为temp。

2) 将temp的下一个指针分配给p的下一指针。

3) 将*p之后节点的下一个指针设置为NULL。

这使得*p之后的节点不存在于链表中,但它仍然占用内存吗?或者,由于在步骤3中我将指针设置为NULL,所以我删除的节点现在没有更多内存了?我需要使用free()还是delete函数?

您似乎在试图描述删除单个链表中的节点。

在您的描述中,正确的是您需要一个指向已删除节点的临时变量。

因此,步骤可以如下。

1) define a temporary pointer to Node and assign the value in p->next to the temporary pointer.
2) assign the value in data member next of the temporary pointer to the data member next of p.
3) delete node pointed to by the temporary pointer.

在C++中,代码将按照以下方式

1) Node *temp = p->next;
2) p->next = temp->next;
3) delete temp;