在这里插入代码片
#include<stdio.h>
/*顺序栈的定义*/
#define MaxSize 50 //定义栈中元素的最大个数
typedef struct{
int data[MaxSize]; //存放栈中元素
int top; //栈顶指针
}SqStack;
/*初始化栈*/
void InitStack(SqStack &S){
S.top = -1; //初始化栈顶指针,也可初始化为S.top=0
}
/*判栈空*/
bool StackEmpty(SqStack S){
if(S.top == -1)
return true;
else
return false;
}
/*入栈*/
bool Push(SqStack &S, int x){
if(S.top == MaxSize-1) //栈满报错
return false;
else
S.data[++S.top] = x; //指针先加1,再入栈
return true;
}
/*出栈*/
bool Pop(SqStack &S, int &x){
if(S.top == -1) //栈空报错
return false;
else
x = S.data[S.top--]; //先出栈,指针再减1
return true;
}
/*读栈顶元素*/
bool GetTop(SqStack S,int &x){
if(S.top == -1) //栈空报错
return false;
else
x = S.data[S.top]; //x记录栈顶元素
return true;
}
int main(){
int value;
SqStack S;
InitStack(S);
StackEmpty(S);
Push(S,2);
Push(S,5);
GetTop(S,value);
printf("GetTop:%d\n",value);
Pop(S,value);
GetTop(S,value);
printf("GetTop:%d\n",value);
return 0;
}
顺序栈的实现(详细注释)
最新推荐文章于 2024-01-14 16:54:00 发布