#include<stdio.h>
#include<stdlib.h>
#define MaxSize 50
#define Elemtype int
typedef struct {
Elemtype data[MaxSize];
int top;
}SqStack;
//初始化栈
void InitStack(SqStack &s){
s.top=-1;
}
//判断栈空
bool StackEmepty(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;
}
//打印栈中数据
bool PrintStack(SqStack s){
if(s.top==-1)
return false;
for(int i=0;i<=s.top;i++){
printf("%d ",s.data[i]);
}
printf("\n");
return true;
}
int main(){
int i,x;
SqStack s;
InitStack(s);
printf("请依次输入数据,用空格间隔,9999结尾:");
scanf("%d",&x);
while(x!=9999){
Push(s,x);
scanf("%d",&x);
}
printf("输入完成,栈中元素如下:\n");
if(!PrintStack(s)){
printf("栈空\n");
}else{
printf("栈非空\n");
}
PrintStack(s);
printf("第一次输出栈顶元素(测试Pop):");
Pop(s,x);
printf("%d\n",x);
printf("第一次输出栈顶元素(测试GetTop):");
GetTop(s,x);
printf("%d\n",x);
}
数据结构代码实践-2.1 顺序栈各功能实现+测试
最新推荐文章于 2022-03-12 10:39:59 发布