从链表的开头删除节点

Deleting a node from the start of a linked list

我正在使用单向链表实现堆栈,其中 Head 位于堆栈顶部,Tail 位于堆栈底部。

我正在执行弹出操作。为此,我必须使头部等于链表中的第二个节点。但是在我这样做之前,我需要先删除链表中的第一个节点。我可以使用 delete head->next;.

来做到这一点

我的问题是,如果我删除了第一个节点,我还能用它移动到下一个节点吗?或者使用已调用 delete 的节点的引用是不好的做法。这是我想用来实现 pop 的代码。

delete head->next;
head->next = head->next->next;

如果你这样做:

delete head->next;

head->next无效。如果您尝试在下一行取消引用它(请记住右侧将在 之前 赋值),您的程序将崩溃。

head->next = head->next->!next; // dereference of the bad pointer happens where I put the !, and you crash there.

如果要删除 head->next 处的对象,您需要先将其保存。

p = head->next;
head->next = head->next->next;
delete p;

首先,东西一删就没了。不要访问已删除的内存。

其次,你为什么说head->next = head->next->nexthead = head->next 不应该足够流行吗?在空列表中,head 会是 nullptr,不是吗?

第三,你为什么不用std::list

最后,操作顺序有时很重要,尤其是当链表可能被多个线程共享时。这就是我实现 pop 的方式(并可选择使其成为多线程安全的):

void list::pop() {
  // optionally, acquire mutex
  node* to_be_deleted = head;
  head = head->next;
  if (head == nullptr) tail = nullptr;
  // release optional mutex here
  delete to_be_deleted;
}