栈的基本操作

当你看到这个时,你会想起你敲过多少遍:

#include <stdio.h>
#include <stdlib.h>
#define ElemType int
#define Status int
#define INIT_SIZE 10	//初始化长度
#define INCRE_SIZE 10	//增量
#define OK 1
#define ERROR 0
#define OVERFLOW -1

typedef struct{
	ElemType *top;	//栈顶指针
	ElemType *base;//栈底指针
	int stackSize;
}SqStack;

//初始化栈
Status InitStack(SqStack &S){
	S.base = (ElemType*)malloc(sizeof(ElemType)*INIT_SIZE);
	if(!S.base){
		exit(OVERFLOW);
	}
	S.top = S.base;//栈顶栈底同时指向底部
	S.stackSize = INIT_SIZE;
	return OK;
}
//取得顶部元素
Status GetTop(SqStack S,ElemType &e){
	if(S.top == S.base){	//栈为空,没有元素
		return ERROR;
	}
	e = *--S.top;//栈顶先减后取值
	return OK;
}
//进栈
Status Push(SqStack &S,ElemType e){
	if(S.top - S.base >= S.stackSize){	//空间已用完
		S.base = (ElemType*)realloc(S.base,sizeof(ElemType)*INCRE_SIZE);//注意这里是realloc重新分配
		if(!S.base){
			exit(OVERFLOW);
		}
		S.top = S.base + S.stackSize;//栈顶重新指向栈顶
		S.stackSize += INCRE_SIZE;
	}
	*S.top++ = e;//否则直接赋值到栈顶后栈顶指针往后移
	return OK;
}
//出栈
Status Pop(SqStack &S,ElemType &e){
	if(S.top == S.base){
		return ERROR;
	}
	e = *--S.top;//先减后取值
	return OK;
}
//判断栈空
Status IsStackEmpty(SqStack S){
	if(S.base == S.top){
		return OK;
	}else{
		return ERROR;
	}
}
//判断栈是否满
Status IsStackFull(SqStack S){
	if(S.top - S.base == S.stackSize){
		return OK;
	}else{
		return ERROR;
	}
}
//获得栈的长度
int GetStackLength(SqStack S){
	return S.top - S.base;
}
//销毁栈
void DestroyStack(SqStack &S){
	S.base = S.top = NULL;
}
//打印栈中元素
void PrintStack(SqStack S){
	ElemType e;
	SqStack ST;//过渡的栈
	InitStack(ST);
	while(S.top != S.base){//将S中的元素逆序
		Pop(S,e);
		Push(ST,e);
	}
	while(ST.top != ST.base){
		Pop(ST,e);
		printf("%d ",e);
	}
	DestroyStack(ST);
	printf("\n");
}
int main(){
	//测试
	SqStack S;
	InitStack(S);
	printf("初始化栈成功...\n");
	ElemType x;
	printf("输入5个数:");
	int i = 5;
	while(i-->0){
		scanf("%d",&x);
		Push(S,x);
	}
	printf("进栈成功\n");
	printf("栈中元素为:");
	PrintStack(S);
	Pop(S,x);
	printf("Pop弹出的元素为:%d\n",x);
	printf("栈中元素为:");
	PrintStack(S);
	GetTop(S,x);
	printf("GetTop的元素为:%d\n",x);
	printf("栈中元素为:");
	PrintStack(S);
	printf("栈的长度为:%d\n",GetStackLength(S));
	DestroyStack(S);
	printf("销毁栈成功\n");
	return 0;
}


运行结果:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值