顺序栈
#include <iostream>
using namespace std;
#define MAXSIZE 100
#define OK 1
#define FALSE 0
#define ERROR -1
#define OVERFLOW -2
typedef int SElemType;
typedef int Status;
typedef struct{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
Status InitStack(SqStack &S){
S.base=new SElemType[MAXSIZE];
if(!S.base)
return FALSE;
S.top=S.base;
S.stacksize=MAXSIZE;
return OK;
}
bool StackEmpty(SqStack S){
if(S.top==S.base)
return true;
else
return false;
}
int StackLength(SqStack S){
return S.top-S.base;
}
Status DestroyStack(SqStack &S){
if(S.base)
{
delete S.base;
S.stacksize=0;
S.base=S.top=NULL;
}
return OK;
}
Status Push(SqStack &S,SElemType e)
{
if(S.top-S.base==S.stacksize)
return OVERFLOW;
*S.top++=e;
return OK;
}
Status Pop(SqStack &S,SElemType &e)
{
if(S.top==S.base)
return ERROR;
e=*--S.top;
return OK;
}
int main(){
int e,n;
SqStack S;
if(InitStack(S))
{
cout<<"顺序栈创建成功!"<<endl;
}
else
{
cout<<"栈创建未成功!"<<endl;
}
cout<<"栈的长度:";
cin>>n;
cout<<"\n输入栈的数据:";
while(n--){
cin>>e;
Push(S,e);
}
cout<<"顺序栈创建成功!"<<endl;
cout<<"\n栈的长度为:";
cout<<StackLength(S)<<endl;
cout<<"\n啰嗦一句:表为空吗:";
if(StackEmpty(S))
cout<<"是!";
else
cout<<"否!";
cout<<endl;
cout<<"输出栈:";
while(!StackEmpty(S)){
Pop(S,e);
cout<<e<<" ";
}
DestroyStack(S);
}