代码步骤是初始化栈,判断栈是否为空,压榨,获取栈顶元素,弹栈。
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#define MAXSIZE 50
typedef int ElemType;
typedef struct{
ElemType data[MAXSIZE];
int top;
}SqStack;
void InitStack(SqStack &S)
{
S.top = -1;//
}
bool StackEmpty(SqStack S)
{
if (-1 == S.top)
{
return true;
}
else
{
return false;
}
}
//入栈
bool Push(SqStack& S,ElemType x)
{
//判断栈是否满了
if (S.top == MAXSIZE - 1)
{
return false;
}
S.data[++S.top] = x;
}
bool GetTop(SqStack S, ElemType &m)
{
if (StackEmpty(S)) {
return false;
}
m = S.data[S.top];
return true;
}
bool Pop(SqStack& S, ElemType& m)
{
if (StackEmpty(S)) {
return false;
}
m = S.data[S.top--];
return true;
}
int main()
{
SqStack S;
InitStack(S);
bool flag;
flag = StackEmpty(S);
if (flag)
{
printf("空\n");
}
Push(S, 3);
Push(S, 4);
Push(S, 5);
ElemType m;
flag = GetTop(S, m);
if (flag)
{
printf("get top%d\n",m);
}
flag = Pop(S, m);
if (flag) {
printf("Pop%d\n", m);
}
return 0;
}