/**
*
* @version:1.0
*/
#include "bits/stdc++.h"
using namespace std;
#define MAXSIZE 100
#define OK 0
#define ERROR -1
typedef struct SqStack {
int *base;
int *top;
} SqStack;
int InitStack(SqStack &S) {
//栈的初始化
S.base = new int[MAXSIZE];
if (S.base == NULL) {
cerr << "顺序栈初始化失败" << endl;
return ERROR;
} else {
S.top = S.base;
cout << "顺序栈初始化成功" << endl;
return OK;
}
}
int Push(SqStack &S, int e) {
//入栈 在顺序栈中插入e
if (S.top - S.base >= MAXSIZE) {
cerr << "栈已经满啦,入栈失败" << endl;
return ERROR;
} else {
*S.top = e;
S.top++;
cout << "入栈成功" << endl;
return OK;
}
}
int Pop(SqStack &S, int &e) {
//出栈
if (S.base == S.top) {
cerr << "栈空,出栈失败" << endl;
return ERROR;
} else {
e = *(--S.top);
cout << "出栈成功" << endl;
return OK;
}
}
int GetTop(SqStack S) {
//取栈顶
if (S.top != S.base) {
return *(S.top - 1);
} else {
return ERROR;
}
}
int main() {
SqStack S;
InitStack(S);
int choice;
do {
cout << "*****************" << endl;
cout << "1.入栈" << endl;
cout << "2.出栈" << endl;
cout << "*****************" << endl;
cout << "请输入您的操作:" << endl;
cin >> choice;
switch (choice) {
case 1: {
int e;
int n;
cout << "请输入元素的个数:" << endl;
cin >> n;
while (n--) {
cout << "请输入您要入栈的元素:" << endl;
cin >> e;
Push(S, e);
}
break;
}
case 2: {
int e;
cout << "元素依次出栈" << endl;
while (S.top != S.base) {
cout << GetTop(S) << "\t";
cout << endl;
Pop(S, e);
}
break;
}
default: {
exit(ERROR);
}
}
} while (1);
return 0;
}