代码如下:
#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);
判断栈空
bool StackEmpty(SqStack S);
判断栈满
bool StackOverflow(SqStack S);
进栈
bool Push(SqStack &S,ElemType x);
出栈
bool Pop(SqStack &S,ElemType &x);
获取栈顶的元素
bool GetTop(SqStack S,ElemType &x);
销毁栈直接另栈顶top指针直接-1; 比较粗暴不写了;
*/
void InitStack(SqStack &S){
S.top = -1;
}
bool StackEmpty(SqStack S){
if(S.top==-1)
return true;
else
return false;
}
bool StackOverflow(SqStack S){
if(S.top==MaxSize-1)
return true;
else
return false;
}
bool Push(SqStack &S,ElemType x){
if(S.top==MaxSize-1)return false;
S.data[++S.top] = x;
return 0;
}
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;
bool flag;
ElemType m;
InitStack(S);
flag=StackEmpty(S);
if(flag){
printf("stack is empty\n");
}
Push(S,3);
Push(S,4);
Push(S,5);
// 注在方法中参数引用可以在调用时,直接传变量
flag=GetTop(S,m);
if(flag){
printf("the top of stack element is %d\n",m);
}
flag=Pop(S,m);
if(flag){
printf("quit stack element is %d\n",m);
}
return 0;
}
/*
输出是
stack is empty
the top of stack element is 5
quit stack element is 5
*/