#include
#define MaxSize 50
typedef int ElemType;
typedef struct {
ElemType data[MaxSize]; //栈中存放元素
int top; //栈顶指针,初始赋为-1
}SqStack; //
/栈初始化/
void InitStack(SqStack& S) {
S.top = -1; //初始化栈顶指针-1
}
/判栈空/
bool StackEmpty(SqStack S) {
return S.top == -1;
}
/元素入栈/
bool Push(SqStack& S, ElemType x) {
if (S.top == MaxSize - 1) { //栈满,报错
return false;
}
S.data[++S.top] = x; //指针先加1,再赋值
return true;
}
/弹栈/
bool Pop(SqStack& S, ElemType& e) {
if (StackEmpty(S)) { //栈空,报错
return false;
}
e = S.data[S.top--]; //先出栈,指针再减一
return true;
}
/读取栈顶元素/
bool GetTop(SqStack S, ElemType& e) {
if (S.top == -1) { //栈空,报错
return false;
}
e = S.data[S.top]; //获取栈顶元素
return true;
}
/清空栈/
bool ClearStack(SqStack& S) {
S.top = -1;
return true;
}
int main() {
SqStack s;
ElemType e;
InitStack(s);
for (int i = 1; i < 10; i++)
Push(s, i);
while (!StackEmpty(s)) {
Pop(s, e);
printf("%d ", e);
}
return 0;
}