使用双链表实现堆栈的错误
a bug for stack implemented with double linked list
class node{
int data;
public:
node *next;
node *prev;
node(int a){data=a; next=NULL; prev=NULL;}
int retrieve(){return data;}
};
class stack{
node *top;
public:
stack(){top=NULL;}
void push(node);
bool empty();
void printall();
};
void stack::push(node a){
if(top==NULL)
top=&a;
else{
top->next=&a;
top->next->prev=top;
top=&a;
}
}
int main(){ stack st; cout<<st.empty()<<endl; node k(3); node j(4); node h(5); st.push(k); st.push(j); st.push(h); st.printall(); }bug发生在push函数。
当我使用gdb在push函数内部跟踪top值时,top的值立即更改为节点a。
我在main函数中只有一个堆栈实例,因此只有一个顶部,它应该保持相同的值,直到我给它赋新值。对吧?
谁能给我点提示吗?(顺便说一句,有没有一种方法可以在代码之前添加4个空格,而不是键入所有空格?)
stack::push(node a)
node x;
/* other things*/
You wil call this as push(x);
你正在按值传递。也许这引起了一些问题。
top=&a;
将存储形式参数的地址。它在push的作用域中,当你退出push函数时,变量将被销毁。
相关文章:
- gdb错误:Backtrace已停止:上一帧与此帧相同(堆栈已损坏?)
- 在 leetcode 上提交解决方案时出现堆栈缓冲区溢出错误
- 我的 int main() 中出现堆栈溢出错误
- 堆栈中大小变量输入错误 (C++)
- 在 gtest 中初始化堆栈上的引用变量的隔离错误
- C++运行时错误与快速排序算法抛出堆栈转储错误
- MSVC __debugbreak() 与 openGL 错误回调一起使用时不会产生调用堆栈
- 在使用堆栈为下一个最大数字编写代码时面临 SIGSEGV(分段错误)
- 使用堆栈从黑客等级中解决平衡括号检查的错误
- 如何在构建对象堆栈时解决转换错误?
- 如何修复递归函数导致的堆栈溢出错误?C++
- C++ 中的构造函数、继承、堆栈、堆、this-pointer 和段错误
- 尝试修改 Hbitmap 数据时出现堆栈错误
- 最后一行执行后的堆栈错误
- 如何捕获所有类型的堆栈错误
- 将中缀转换为后缀:无法识别堆栈错误
- 到达主函数结束后发生调试运行时堆栈错误
- 使用链表堆栈错误
- 在c++中计算后缀表达式时接收堆栈错误
- 线程堆栈错误