我正在尝试使用底层链表结构创建一个 Stack。
也许我错了,但我在使用 remove() 函数时遇到了问题。
int Stack::remove(){
node* victim = new node;
int popped;
popped = top->element;
victim = top;
top = victim->next;
delete victim;
return popped;
}
我正在检测 glibc
double free or corruption (out);
既然我正在为 victim 分配新内存,我是否不必删除 victim,或者这是我不必担心的事情?
最佳答案
一堆很像一堆正在洗的盘子,一个盘子放在另一个盘子上。即先入后出(FILO数据类型)。也就是说,如果您的堆栈读入 2、7、8,那么它将显示为:
8
7
2
也就是说,首先将 2 放入堆栈,然后是 7,然后是 8。如果要移除或弹出堆栈,则需要移动指针的头部。你的代码对我来说有点奇怪......
int Stack::remove()
{
int datum; //to store the popped value
node* temp=head; //assign pointer to head of list
datum = temp->data; //grab the data value stored at the head (or temp since they carry same reference)
head = temp->next; //move the head pointer (in our example now it points to 7)
delete temp;
return datum;
}
关于c++ - 链表实现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2166587/