//顺序栈
#include<iostream>
#include<string>
using namespace std;
#define MAXSIZE 100
typedef struct{
int *base;
int *top;
int stacksize;
}SqStack;
//初始化栈
int InitStack(SqStack &S)
{
S.base = new int[MAXSIZE];
if(S.base == nullptr)
{
cout<<"分配空间失败"<<endl;
return 0;
}
S.top = S.base;
S.stacksize = MAXSIZE;
return 1;
}
//判断栈是否为空
int IsEmpty(SqStack &S)
{
if(S.base == S.top)
{
cout<<"栈为空"<<endl;
return 0;
}
else
{
return 1;
}
}
//栈的长度
int StackLength(SqStack &S)
{
return S.top-S.base;
}
//清空顺序栈
int ClearStack(SqStack &S)
{
if(S.base !=nullptr)
{
S.top = S.base;
}
return 0;
}
//销毁栈
int DestoryStack(SqStack &S)
{
if(S.base != nullptr)
{
delete S.base;
S.stacksize = 0;
S.base = S.top = NULL;
}
return 1;
}
//入栈
int PushStack(SqStack &S,int e)
{
if(S.top-S.base == MAXSIZE)
{
cout<<"栈满"<<endl;
return 0;
}
*S.top = e;
S.top++;
return 1;
}
//出栈
int PopStack(SqStack &S)
{
if(S.base == S.top)
{
cout<<"栈空"<<endl;
return 0;
}
S.top--;
int x = *S.top;
cout<<"出栈数据为:"<<x<<endl;
return 1;
}
int main()
{
SqStack S;
// 初始化栈
if (InitStack(S)) {
cout << "栈初始化成功" << endl;
} else {
cout << "栈初始化失败" << endl;
return -1;
}
// 判断栈是否为空
if (IsEmpty(S)) {
cout << "栈不为空" << endl;
}
// 入栈操作
PushStack(S, 10);
PushStack(S, 20);
PushStack(S, 30);
// 栈的长度
cout << "栈的长度为:" << StackLength(S) << endl;
// 出栈操作
PopStack(S);
PopStack(S);
// 清空栈
ClearStack(S);
if (IsEmpty(S)) {
cout << "栈不为空" << endl;
}
// 销毁栈
DestoryStack(S);
cout << "栈已销毁" << endl;
return 0;
}