数据结构代码实践-2.1 顺序栈各功能实现+测试

#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);
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值