顺序栈的基本操作(C语言实现)
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
#define OVERFLOW -1
#define OK 1
#define ERROR 0
typedef int SElemtype;
typedef int Status;
typedef struct{
SElemtype *top,*base;
int stacksize;
}Sqstack;
Status InitStack(Sqstack &S){
S.base=(SElemtype *)malloc(sizeof(SElemtype)*MAXSIZE);
if(!S.base)
exit(OVERFLOW);
S.top=S.base;
S.stacksize=MAXSIZE;
printf("初始化成功\n");
return OK;
}
void EmptyStack(Sqstack S){
if(S.top=S.base)
printf("栈为空\n");
else
printf("栈不为空\n");
}
Status LengthStack(Sqstack S){
return S.top-S.base;
}
Status ClearStack(Sqstack &S){
if(S.base)
S.top=S.base;
printf("清空栈成功\n");
return OK;
}
Status DestroyStack(Sqstack &S){
if(S.base){
free(S.base);
S.base=S.top=NULL;
S.stacksize=0;
}
printf("销毁栈成功\n");
return OK;
}
Status Push(Sqstack &S,SElemtype e){
if(S.top-S.base==S.stacksize)
return 0;
*S.top++=e;
printf("入栈成功\n");
return OK;
}
Status Pop(Sqstack &S,SElemtype &e){
if(S.base=S.top)
return ERROR;
e=*--S.top;
return OK;
}
int main()
{
Sqstack S;
InitStack(S);
EmptyStack(S);
printf("栈的长度为%d\n",LengthStack(S));
ClearStack(S);
SElemtype e,a=1;
Push(S,a);
printf("出站元素为%d\n",e);
}
