我使用单链表实现堆栈,其中Head位于堆栈的顶部,Tail位于堆栈的底部。
我正在实施一个pop操作。为了做到这一点,我必须使头部等于链表中的第二个节点。但在此之前,我需要先删除链表中的第一个节点。我可以使用delete head->next;
执行此操作。
我的问题是,如果删除第一个节点,我还可以使用它继续下一个节点吗?或者使用已经调用delete
的节点的引用是不好的做法。这是我想用来实现pop的代码。
delete head->next;
head->next = head->next->next;
答案 0 :(得分:3)
如果你这样做:
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;
答案 1 :(得分:1)
首先,一旦删除某些内容,它就会消失。不要访问已删除的内存。
其次,你为什么要说head->next = head->next->next
?不应该head = 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;
}