参考王道《2023年数据结构考研复习指导》
#include <iostream>
#define MaxSize 10
typedef int ElemType;
typedef struct {
ElemType data[MaxSize];
int top;
} SqStack;
// 初始化栈
void InitStack(SqStack& S) {
S.top = -1; // 栈顶指针初始化为-1
}
// 判断栈空
bool StackEmpty(SqStack S) {
if (S.top == -1)
return true;
else
return false;
}
// 进栈操作——新元素入栈
bool Push(SqStack& S, ElemType x) {
if (S.top == MaxSize) // 栈满,报错
return false;
S.data[++S.top] = x;
return true;
}
// 出栈操作
bool Pop(SqStack& S, ElemType& x) {
if (S.top == -1) // 栈空,报错
return false;
x = S.data[S.top--];
return true;
}
// 读栈顶操作
bool GetTop(SqStack S, ElemType& x) {
if (S.top == -1) // 栈空,报错
return false;
x = S.data[S.top];
return true;
}
int main() {
SqStack S;
InitStack(S);
Push(S, 1);
Push(S, 2);
Push(S, 3);
int x = -1;
Pop(S, x);
std::cout << x << std::endl;
GetTop(S, x);
std::cout << x << std::endl;
system("pause");
return 0;
}