#include <iostream>
#include <Windows.h>
using namespace std;
#define MAXSIZE 6
//顺序栈的实现
typedef struct {
int* base;
int* top;
int stacksize;
int Length;
}SQstack;
//初始化
void Initstack(SQstack& S) {
S.base = new int[MAXSIZE];
S.top = S.base;
S.stacksize = MAXSIZE;
S.Length = 0;
}
//入栈
bool InsertStack(SQstack& S,int e) {
if (S.top - S.base == S.stacksize) {
cout << "栈已满,无法入栈!";
return false;
}
//*(S.top++) = e;
*S.top = e;
S.top++;
S.Length++;
return true;
}
//出栈
bool DeleteStack(SQstack& S, int &e) {
if (S.base == S.top) {
cout << "栈为空,无法出栈!" << endl;
return false;
}
S.top--;
e = *S.top;
//e = *(--S.top);
S.Length--;
return true;
}
//获取栈顶元素
void getTop(SQstack& S,int &e) {
e = *(S.top-1);//返回栈顶元素的值,栈顶指针不变
cout <<"栈顶元素为:"<< e << " ";
cout << endl;
}
//判断栈是否为空
bool EmptyStack(SQstack& S) {
return S.base == S.top;
}
//销毁顺序栈
void Destory(SQstack& S) {
if (S.base) {
delete S.base;
S.base = NULL;
}
}
//获取顺序栈的长度
int getLnegth(SQstack& S) {
return S.Length;
}
void showMenu() {
cout << "\t顺序栈的基本操作" << endl;
cout << "0.退出" << endl;
cout << "1.入栈" << endl;
cout << "2.出栈" << endl;
cout << "3.获取栈顶元素" << endl;
cout << "4.判断栈是否为空" << endl;
cout << "5.返回栈的元素个数" << endl;
}
int main() {
SQstack Q;
int choose = 0;
int e = 0;//要入栈的元素
int n = 0;//入栈的元素个数
int e1 = 0;//出栈的元素
int e2 = 0;//栈顶元素
Initstack(Q);
showMenu();
bool flag = -1;
while (flag) {
cout << "请选择:";
cin >> choose;
switch (choose)
{
case 1:
cout << "请输入要入栈的元素个数:";
cin >> n;
while (n > 0) {
cout << "请输入要入栈的元素:";
cin >> e;
if (InsertStack(Q, e)) {
cout << "元素入栈成功!" << endl;
}
else {
cout << "元素入栈失败!" << endl;
}
n--;
}
break;
case 2:
cout << "出栈------" << endl;
if (DeleteStack(Q, e1)) {
cout << "出栈的元素 :" << e1 << endl;
}
break;
case 3:
getTop(Q, e2);
break;
case 4:
if (EmptyStack(Q)) {
cout << "顺序栈为空!" << endl;
}
else {
cout << "顺序栈不为空!" << endl;
}
break;
case 5:
cout << "顺序栈的长度为:" << getLnegth(Q) << endl;
break;
case 0:
default:
cout << "退出系统!" << endl;
flag = 0;
}
}
cout << "销毁顺序表----" << endl;
Destory(Q);
system("pause");
return 0;
}