#include<stdio.h>
#define MAXSIZE 50
#define ElemType int
typedef struct {
ElemType data[MAXSIZE];
int top;
}sqStack;
sqStack S;
// 初始化
void InitStack(sqStack &S){
S.top = -1;
// 初始值设置为了-1,
// 设置为 0 也可,
// 相应的,top指向栈顶元素的下一个存储单元
}
// 判断栈为空
bool StackEmpty(sqStack &S){
if(S.top == -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 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(){
// 初始化
InitStack(S);
printf("此时栈顶指针是:%d\n",S.top);
// 添加两个元素
Push(S,1);
Push(S,2);
// 获取栈顶元素
int x; // 存取栈顶元素值
GetTop(S,x);
printf("获取栈顶元素:%d\n",x);
// 弹出栈顶元素
Pop(S,x);
printf("弹出栈顶元素:%d\n",x);
Pop(S,x);
printf("弹出栈顶元素:%d\n",x);
// 查看当前栈是否为空栈
if(StackEmpty(S)){
printf("当前为空栈\n");
}else {
printf("当前栈不为空\n");
}
return 0;
}
王道数据结构--顺序栈代码实现整理
最新推荐文章于 2024-08-03 19:28:58 发布