1、结构体定义

2、初始化栈

3、栈空判断

4、入栈

5、出栈

6、获取栈顶元素

完整程序如下
#include<stdio.h>
#include<stdlib.h>
#define Maxsize 50
typedef int ElemType;
typedef struct Stack{
ElemType data[Maxsize];
int top;
}SqStack;
void InitStack(SqStack& S) {
S.top = -1;
}
bool StackIsEmpty(SqStack S) {
if (S.top == -1) {
return true;
}
return false;
}
bool Push(SqStack& S, ElemType data) {
if (S.top == Maxsize-1) {
return false;
}
S.data[++S.top] = data;
return true;
}
void PrintStack(SqStack S) {
for (int i = 0; i <= S.top; i++) {
printf(" %d ",S.data[i]);
}
printf("\n");
}
bool GetTop(SqStack S,ElemType& e) {
if (StackIsEmpty(S)) {
return false;
}
e = S.data[S.top];
return true;
}
bool Pop(SqStack& S,ElemType& e) {
GetTop(S,e);
S.top--;
return true;
}
int main() {
SqStack S;
InitStack(S);
Push(S, 3);
Push(S, 4);
Push(S, 5);
PrintStack(S);
ElemType e;
GetTop(S,e);
PrintStack(S);
printf("%d\n",e);
Pop(S,e);
PrintStack(S);
printf("%d\n", e);
return 0;
}