#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 10
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 0;
S.top=S.base;
S.stacksize=MAXSIZE;
return 1;
}
//判空
Status StackEmpty(SqStack S){
if(S.base==S.top){
return 1;//返回1栈空
}
else{
return 0;//栈不为空
}
}
//求栈的长度
int StackLength(SqStack S) {
return S.top-S.base;
}
//清空顺序栈
Status ClearStack(SqStack &S) {
if(S.base) S.top=S.base;//如果栈存在就清空
return 1;
}
//销毁栈
Status DestoryStack(SqStack &S){
if(S.base) {//如果栈存在就销毁
delete S.base;
S.top=S.base=NULL;
S.stacksize=0;
return 1;
}
}
//入栈
Status Push(SqStack &S,SElemType e) {
if(S.top-S.base==S.stacksize){//判断是否栈满
return 0;
}
*S.top++=e ;
return 1;
}
//出栈
Status Pop(SqStack &S,SElemType &e) {
if(S.base==S.top){//判栈空?
return 0;
}
e=*--S.top ;
return 1;
}
main(){
//初始化栈
SqStack S;
int n=InitStack(S);
printf("%d",n);
//栈空
n=StackEmpty(S);
if(n==1){
printf("\n栈空") ;
}
//栈长度
n=StackLength(S);
printf("\n栈的长度%d",n);
// //清空栈
// n=ClearStack(S);
// if(n==1){
// printf("\n栈已清空");
// }
//
// //销毁栈
// n=DestoryStack(S) ;
// if(n==1){
// printf("\n栈已销毁");
// }
//入栈
n=Push(S,2) ;
if(n==1){
printf("\n入栈成功");
}
//出栈
int e;
n=Pop(S,e) ;
if(n==1) {
printf("\n出栈的元素为:%d",e);
}
}
栈-栈的顺序表示和实现
于 2024-07-25 15:40:10 首次发布