我写了一个实现栈基本操作的程序,但是里面的那个DispStack函数总是有问题,请各位帮帮忙吧
#include <iostream>#define ERROR 0
#define OK 1
#define STACK_INIT_SIZE 20
#define STACKINCREMENT 1
#define OVERFLOW -2
using namespace std;
typedef int SElemType;
typedef struct SqStack{
struct SqStack *base;
struct SqStack *top;
int stacksize;
int data;
}STACK, *PSTACK;
int Push(SqStack &S,SElemType &e)//入栈
{
if(S.top-S.base>=S.stacksize)
{
S.base=(PSTACK) malloc (sizeof(SqStack));
if(!S.base)exit(OVERFLOW);
S.top=S.base+S.stacksize;
S.stacksize+=STACKINCREMENT;
}
S.top->data=e;
S.top++;
return OK;
}
int Pop(SqStack &S,SElemType &e)//出栈
{
if(S.top==S.base) return ERROR;
e=--S.top->data;
return OK;
}
int GetTop(SqStack S,SElemType &e)//获取栈顶元素
{
if(S.top=S.base) return ERROR;
e=(S.top-1)->data;
return e;
}
int Length(SqStack S)//返回栈的深度
{
return(S.top-S.base);
}
int DestroyStack(SqStack &S)//销毁栈S
{
free(S.base);
S.top=S.base=NULL;
S.stacksize=0;
return OK;
}
int ClearStack(SqStack &S)//清空栈S
{
S.top=S.base;
return OK;
}
int InitStack(SqStack &S)//构造一个空栈
{
S.base=(PSTACK) malloc (sizeof(SqStack));
if(!S.base) exit (OVERFLOW);
S.top=S.base;
S.stacksize=STACK_INIT_SIZE;
return OK;
}
int StackEmpty(SqStack S)//判断是否为空栈
{
if(S.top=S.base)
{ cout<<"栈为空栈";
return true;
}
else
{ cout<<"栈非为空栈";
return false;
}
}
int StackFull(SqStack S)//判断是否已满
{
if(S.top=S.base+S.stacksize)
return true;
else
return false;
}
int DispStack(SqStack &S)//尤其是这个函数有问题
{
SqStack *p;
for(p=S.top-1;S.top>=S.base;S.top--)
cout<<p->data<<endl;
return OK;
}
int main()
{
int i;
int e,n;
SqStack S;
InitStack(S);
cout<<"请输入要入栈的元素个数:"<<endl;
cin>>n;
for(i=1;i<=n;i++)
{ cout<<"请输入元素:";
cin>>e;
Push(S,e);
}
DispStack(S);
for(;;)
{
cout<<"0,入栈;"<<endl<<"1,出栈;"<<endl<<"2,清空栈;"<<endl<<"3,销毁栈;"<<endl<<"4,判断栈是否为空;"<<endl<<"5,判断栈是否已满;"<<endl<<"6,获取栈顶元素;"<<endl<<"7,返回栈的深度"<<endl;
cout<<"请输入操作选择:"<<endl;
cin>>i;
while(i<0||i>7)
{
cout<<"输入错误,请重新输入:"<<endl;
}
switch(i)
{
case 0:
{int e;
cout<<"输入将要入栈的元素:"<<endl;
cin>>e;
Push(S,e);
DispStack(S);
break;
}
case 1:
{int e;
Pop(S,e);
DispStack(S);
break;
}
case 2:
{ClearStack(S);
break;
}
case 3:
{DestroyStack(S);
break;
}
case 4:
{StackEmpty(S);
break;
}
case 5:
{StackFull(S);
break;
}
case 6:
{int e;
GetTop(S,e);
cout<<e<<endl;
break;
}
case 7:
{Length(S);
cout<<S.top-S.base<<endl;
break;
}
}
}
return 0;
}