c++ - 链表实现问题

标签 c++ memory linked-list allocation

我正在尝试使用底层链表结构创建一个 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/

相关文章:

c++ - C++编译器是否优化顺序静态变量读取?

memory - 使用自定义 Lua 分配器计算内存使用情况,但其结果与 collectgarbage ('count' 不同)

c++ - 用于通过快速迭代按值从任何位置删除的容器

java - 扩展链接列表方法在单独的类 main 方法中不起作用

c - 如何仅使用指针(无结构)来实现链表?

c++ - 为什么我必须专门化它?

c++ - C++ 中的 Linux 进程加载器

Java 堆空间(带有大文件的 CMS)

c++ - 强制 visual studio 链接器保持名称修改

c - C 中的内存泄漏