直接上代码
#include<stdio.h>
#include<stdlib.h>
#define true 1
#define false 0
#define overFlow -2
#define MAXSIZE 100
#define OK 1
typedef int Status;
typedef int SElemType;
typedef struct{
SElemType *base;
SElemType *top;
int stacksize;
}Sqstack;
Status InitStack(Sqstack &s)//顺序栈的初始化
{
s.base=new SElemType[MAXSIZE];
if(!s.base)
exit(overFlow);
s.top=s.base;
s.stacksize=MAXSIZE;
return OK;
}
//判断是否为非空栈
Status StackEmpty(Sqstack &s)
{
if(s.top==s.base)
return true;
else
return false;
}
//销毁顺序栈
Status DestoryStack(Sqstack &s)
{
if(s.base)
{
delete s.base;
s.stacksize=0;
s.base=s.top=NULL;
}
return OK;
}
int Stacklength(Sqstack s)
{
return s.top-s.base;
}
//清空顺序栈
Status clearStack(Sqstack s)
{
if(s.base)
s.top=s.base;
}
//顺序栈入栈
Status Push(Sqstack &s,SElemType e)
{
if(s.top-s.base==s.stacksize)
return false;
*s.top=e;
s.top++;
}
//顺序栈出栈
Status PoP(Sqstack &s,SElemType &e){
if(s.top==s.base)
return false;
// --s.top;
// e=*s.top;
e=*--s.top;
return OK;
}
int main()
{
Sqstack s;
SElemType e=0;
if(InitStack(s))
printf("Initstack success\n");
//执行入栈操作
e=11;
Push(s,e);
e=22;
Push(s,e);
e=33;
Push(s,e);
if(StackEmpty(s))
{
printf("empty stack\n");
}
else
{
printf("stack is not empty\n");
}
printf("the length of the stack is %d\n",Stacklength(s));
PoP(s,e);
printf("the pop element is %d\n",e);
if(clearStack(s));
printf("clear success!\n");
if(DestoryStack(s))
{
printf("destoryStack success!\n");
}
return 0;
}