0

我正在尝试使用底层链表结构制作堆栈。

也许我错了,但我在使用 remove() 函数时遇到了问题。

int Stack::remove(){  
  node* victim = new node;  
  int popped;  
  popped = top->element;  
  victim = top;
  top = victim->next;  
  delete victim;  
  return popped;  
}

我正在检测 glibc

双重免费或腐败(出局);

由于我正在为受害者分配新内存,我不必删除受害者,还是我不必担心?

4

3 回答 3

2

一摞很像一堆正在被清洗并相互叠放的盘子。即第一个入是最后一个出(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;
 }
于 2010-01-30T02:43:47.033 回答
1

没有理由remove()像使用victim. 你想要的是:

int Stack::remove(){  
  node* new_top = top->next;
  int popped = top->element;

  delete top;  
  top = new_top;

  return popped;  
}
于 2010-01-30T02:37:31.353 回答
1

您无需为victim. 只需将堆栈的顶部分配给它,如果不是null,则将其设置topnext指针,从中检索值victim,然后释放victim.

这实际上不是损坏,而是内存泄漏-您正在分配一个节点,然后覆盖该指针,victim = top;从而丢失了刚刚分配的内存的跟踪。

于 2010-01-30T02:41:09.457 回答