数据结构—栈的顺序的实现

#include<stdio.h>   
#include<stdlib.h>
#define Stack_size 100			//栈的初始容量
#define stackIncrease 10		//每次的增量
typedef int Elemtype;
typedef struct{                
	Elemtype *base;   
	Elemtype *top;
	int stacksize;
}Sqstack;

bool InitStack(Sqstack &S){		//初始化栈
	S.base = (Elemtype *)malloc(Stack_size*sizeof(Elemtype));
	if(!S.base)
		return false;
	S.top = S.base;
	S.stacksize = Stack_size;
	return true;
}

void ClearStack(Sqstack &S){   //清空栈的元素   实际上只移动了一下指针 
	S.top = S.base;	
}
bool StackEmpty(Sqstack S){   //判断栈是否为空
	if(S.base == S.top)
		return true;
	else
		return false;
}
int StackLength(Sqstack S){  				//返回栈的长度
	return S.top - S.base;
}
bool GetTop(Sqstack &S, Elemtype &e){     //得到栈顶元素, 并用e返回
	if(S.base == S.top)  	//栈为空
		return false;
	e = *(S.top - 1);
	return true;
}
bool Push(Sqstack &S, Elemtype e){    	//将元素e入栈
	if(S.top - S.base >= S.stacksize){
		S.base = (Elemtype *)realloc(S.base, (S.stacksize + stackIncrease)*sizeof(Elemtype));
		if(!S.base)
			return false;
		S.top = S.base + S.stacksize;
		S.base += stackIncrease;
	}
	*S.top = e;      
	S.top++;
	//*(S.top++) = e; //这两条语句可以合并 			 
	return true;
}
bool Pop(Sqstack &S, Elemtype &e){     //删除栈顶元素, 并用e返回
	if(S.base == S.top)  
		return false;
	e = *(--S.top);
	return true;
}



int main(){
	Sqstack S;	
	int e;
	if(InitStack(S) == true){
		printf("栈已经初始化好啦,请输入你想往进放的元素:\n");
		printf("温馨提示:输入-1代表停止输入\n");
	}
	while(scanf("%d", &e) && e != -1){
		Push(S, e);
	}
	printf("栈的长度是:%d\n", StackLength(S));
	printf("请输入你想要进行的操作序号:\n");
	printf("1:添加元素,2:删除栈顶元素,3:取栈顶元素,4:判断栈是否为空,\n5:返回栈的长度,6:清空栈,7:退出\n");
	int n;
	while(scanf("%d", &n) && n != 7){
		switch(n){
			case 1:
				printf("请输入你想添加的元素:");
				scanf("%d", &e);
				if(Push(S, e) == true)
					printf("添加成功\n");
				else
					printf("添加失败\n");
				break;	 
			case 2:
				if(Pop(S, e) == true){
					printf("删除成功,删除的元素是:%d\n", e);
				}
				else
					printf("删除失败\n");
				break;
			case 3:
				if(GetTop(S, e) == true)
					printf("栈顶元素是:%d\n", e);
				else
					printf("操作失败\n");
				break;
			case 4:
				if(StackEmpty(S) == true)
					printf("栈为空\n");
				else
					printf("栈不为空\n");
				break; 
			case 5:
				printf("栈的长度是:%d\n", StackLength(S));
				break;
			case 6:
				ClearStack(S);
				printf("清空成功\n");
				break; 
			default:
				printf("输入有误,请重新输入\n");
				break;
		}	
	}
	printf("谢谢你的使用!\n");
	return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值