#include<iostream>
using namespace std;
typedef int SElemType; //取别名
#define ERROR 0
#define OK 1
#define MAXSIZE 100
//定义
typedef struct{
SElemType *base;
SElemType *top;
int stackSize;
}SqStack;
//初始化
int InitStack(SqStack &S){
S.base=new SElemType[MAXSIZE];
if(!S.base)
return ERROR;
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;
}
//入栈
int Push(SqStack &S,SElemType e){
if(S.top-S.base==S.stackSize)//栈满
return ERROR;
*S.top++=e;
return OK;
}
//出栈
int Pop(SqStack &S,SElemType &e){
if(S.top==S.base)//栈空
return ERROR;
e=*--S.top;
return OK;
}
//取栈顶元素
int GetTop(SqStack &S,SElemType &e){
if(S.top==S.base)
return ERROR;
e=*(S.top-1);
return OK;
}
int main()
{
SqStack s;
bool flag;
SElemType e;
//初始化
InitStack(s);
cout<<"栈的长度为:"<<s.stackSize<<endl;
//判空
flag=StackEmpty(s);
if(flag)
cout<<"栈空"<<endl;
else
cout<<"栈非空"<<endl;
//求栈长
cout<<"栈的长度为:"<<StackLength(s)<<endl;
//入栈
cout<<"请填写入栈的数据:"<<endl;
cin>>e;
while(e!=-9999){
Push(s,e);
cout<<"请填写入栈的数据:"<<endl;
cin>>e;
}
//取栈顶元素
GetTop(s,e);
cout<<"栈顶元素为:"<<e<<endl;
//出栈
while(!StackEmpty(s)){
Pop(s,e);
cout<<e<<" ";
}
return 0;
}
数据结构:顺序栈
于 2024-04-18 10:00:36 首次发布