#include<iostream>
using namespace std;
struct list
{
int data; struct list *next;
};
class Stack
{
struct list *ptrf,*ptrb;
public:
Stack()
{
ptrf=ptrb=NULL;
}
void push(int x)
{
struct list *newnode=new struct list;
newnode->data=x;
newnode->next=NULL;
if(ptrb==NULL)
ptrf=ptrb=newnode;
else
{
ptrb->next=newnode;
ptrb=newnode;
}
}
int pop()
{
//struct list *top;
int value;
value=ptrf->data;
//top=ptrf;
ptrf=ptrf->next;//因为19行代码说是NULL,那么这里的ptrf不就也为NULL了?
//delete top;
return value;
}
};
void main()
{
Stack A; int i;
int arr[]={5,2,8,1,4,3,9,7,6};
cout<<"入队顺序:";
for(i=0;i<9;i++)
{
cout<<arr[i]<<" ";
A.push(arr[i]);
}
cout<<endl<<"出队顺序:";
for(i=0;i<9;i++)
cout<<A.pop()<<" ";
cout<<endl;
system("pause");
}
初始化时:ptrf=ptrb=NULL;
有了第一个节点:ptrf=ptrb=newnode;
以后有新节点:ptrf不变,ptrb=newnode;
首先你的代码思路有问题,就是没有判空,如果栈空的话,ptrf 与 ptrb 指针均为空,这样的话,你执行pop方法,就会因为非法访问内存而报错。
其次,你要知道newnode 跟 ptrf 仅仅是不同的指针指向了相同的内存位置,并且34行的代码里面ptrf 一定不是空,ptrf->next 有可能是空。好好理解理解
代码逻辑。
一个是栈顶指针ptrb,一个是栈底指针ptrf
你用的是链式栈,就是链表实现的
所以在pop的时候,需要从栈底检索到栈顶的前一个
之后才行,当然还有楼上所说,还有空栈的情况需要考虑,因为是链式栈,所以满栈就不要考虑了