使用双链表实现堆栈的错误

a bug for stack implemented with double linked list

本文关键字:堆栈 错误 实现 链表      更新时间:2023-10-16
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函数时,变量将被销毁。