/**
* @author:
* @version:1.0
*/
#include "bits/stdc++.h"
using namespace std;
#define OK 0
#define ERROR -1
typedef struct StackNode {
int elem;
struct StackNode *next;
} StackNode, *LinkStack;
int InitStack(LinkStack &S) {
//构造一个空栈
S = NULL;
cout << "链栈已经初始化" << endl;
return OK;
}
int StackEmpty(LinkStack S) {
//判断栈空
if (S == NULL) {
cout << "链栈为空" << endl;
} else {
cout << "链栈不为空" << endl;
}
return OK;
}
int Push(LinkStack &S, int e) {
//入栈
LinkStack p = new StackNode;
if (p == NULL) {
cerr << "结点创建失败" << endl;
return ERROR;
}
p->elem = e;//将新的节点的数据域设置为e
p->next = S;//将新节点插入栈顶
S = p;//修改栈顶指针
cout << "入栈成功" << endl;
return OK;
}
int Pop(LinkStack &S) {
//弹栈
if (S == NULL) {
cerr << "弹栈失败" << endl;
return ERROR;
}
LinkStack p = S;
S = S->next;
delete p;
cout << "弹栈成功" << endl;
return OK;
}
int GetTop(LinkStack S) {
//取栈顶
if (S != NULL) {
return S->elem;
}
}
int main() {
LinkStack S;
InitStack(S);
int choice;
do {
cout << "*****************" << endl;
cout << "1.入栈" << endl;
cout << "2.出栈" << endl;
cout << "3.判断栈空" << endl;
cout << "4.取栈顶" << endl;
cout << "*****************" << endl;
cout << "请输入您的操作:" << endl;
cin >> choice;
switch (choice) {
case 1: {
int e;
cout << "请输入您要入栈的元素:" << endl;
cin >> e;
Push(S, e);
break;
}
case 2: {
Pop(S);
break;
}
case 3: {
StackEmpty(S);
break;
}
case 4: {
int res = GetTop(S);
cout << "栈顶元素为:" << res << endl;
break;
}
default: {
exit(ERROR);
}
}
} while (1);
return 0;
}