/*
顺序栈-HXT
*/
#define _CRT_SECURE_NO_WARNINGS //调用c语言的语法,在其他IDE可以引入c的头文件代替
#include<iostream>
#include<string.h>
using namespace std;
#define OK 0
#define ERROR 1
const int MAXSIZE = 100;
typedef string SElemType;
typedef int status;
typedef struct SqStack //定义栈
{
SElemType* base;
SElemType* top;
int StackSize;
};
//初始化
status InitStack(SqStack &S);
//压栈
status Push(SqStack&S, SElemType& e);
//弹栈
status Pop(SqStack& S, SElemType& e);
//销毁
status DestroyStack(SqStack& S);
//清空
status ClearStack(SqStack& S);
//判空
status StackEmpty(SqStack& S);
//长度
status StackLength(SqStack& S);
//取栈顶
status GetTop(SqStack& S, SElemType& e);
int main()
{
SqStack S;
int a;
SElemType e;
InitStack(S);
cout << "1.压栈" << "\n"
<< "2.弹栈" << "\n"
<< "3.长度" << "\n"
<< "4.清空" << "\n"
<< "5.销毁" << "\n"
<< "6.判空" << "\n"
<< "7.取栈顶" << "\n"
<< "8.退出" << endl;
while (1)//一直循环,直到选择退出
{
cout << "请选择:" << endl;
cin >> a;
switch (a)
{
case 1:
cout << "请输入学生名字:" << endl;
cin >> e;
Push(S, e);
break;
case 2:
Pop(S, e);
cout << "弹出为:" << e << endl;
break;
case 3:
StackLength(S);
break;
case 4:
ClearStack(S);
break;
case 5:
DestroyStack(S);
break;
case 6:
StackEmpty(S);
break;
case 7:
GetTop(S,e);
break;
case 8:
break;
}
if (a == 8)break;
}
return 0;
}
//初始化栈
//为S.base用new分配一定空间,且top=base
status InitStack(SqStack& S)
{
S.base = new SElemType[MAXSIZE];
if (!S.base)exit(OVERFLOW);//储存分配失败
S.top = S.base;
S.StackSize = MAXSIZE;
cout << "初始化成功!" << endl;
return OK;
}
//判空
status StackEmpty(SqStack& S)
{
if (S.top == S.base)cout << "栈为空" << endl;
else cout << "栈不为空" << endl;
return OK;
}
//长度
status StackLength(SqStack& S)
{
cout << "栈的长度为:"<< S.top-S.base << endl;
return S.top - S.base;
}
//清除顺序栈
//形式主义上的清除
status ClearStack(SqStack& S)
{
if (S.base)S.top = S.base;
S.StackSize = 0;
cout << "清除顺序栈成功!" << endl;
return OK;
}
//销毁顺序栈
status DestroyStack(SqStack& S)
{
if (S.base) {
delete[] S.base;
S.StackSize = 0;
S.base = S.top = NULL;
}
cout << "销毁顺序栈成功!" << endl;
return OK;
}
//压栈
status Push(SqStack& S, SElemType& e)
{
if (S.top - S.base == MAXSIZE)//栈满
{
cout << "栈已满!" << endl;
return ERROR;
}
*S.top = e;
S.top++;
return OK;
}
//弹栈
status Pop(SqStack& S, SElemType& e)
{
if (S.top == S.base)return ERROR;
--S.top;
e = *S.top;
return OK;
}
//取栈顶
status GetTop(SqStack& S, SElemType& e)
{
if (S.top == S.base)return ERROR;
--S.top;
e = *(S.top);
++S.top;
cout << "栈顶元素为:" << e << endl;
return OK;
}