顺序栈

#include<stdio.h>
#define MaxSize 20
typedef struct SqueueStack {
	int data[MaxSize];
	int top;
} SqStack;

//初始化栈
void initSqStack(SqStack &S) {
	S.top=-1;
}

//判断栈空
bool StackEmpty(SqStack S) {
	if(S.top==-1) {
		return true;
	} else {
		return false;
	}
}

//入栈 push
bool Push(SqStack &S,int x) {
	if(S.top == MaxSize-1) {
		return false;
	}
	S.top =S.top+1;
	S.data[S.top]=x;
	return true;
}

//出栈 pop
bool Pop(SqStack &S,int &e) {
	if(StackEmpty(S)) {
		printf("栈为空");
		return false;
	}
	e=S.data[S.top];
	S.top=S.top-1;
	return true;
}

//获取栈顶元素 GetTop
int GetEle(SqStack S) {
	if(StackEmpty(S)) {
		printf("栈为空");
		return 0;
	}
	int x=S.data[S.top];
	return x; 
}

//销毁栈 DestroyStack
bool DestoryStack(SqStack &S){
	for(int i=0;i<S.top;i++){
		S.data[i]=0;
	}
	S.top=-1;
	return true;
}

//栈的长度
int Length(SqStack S){
	int length = S.top;
	return length;
} 

//打印栈
void PrintStack(SqStack S) {

	if(StackEmpty(S)){
		printf("栈为空!");
		return ;
	}
	
    printf("从栈顶元素开始,栈如下:\n");
    while (S.top > 0) {//注意判空的条件
        printf("S[%d]=%d\n", S.top, S.data[S.top--]);
    }
    printf("栈打印完毕\n");
}


int main() {
	SqStack S;
	initSqStack(S);
	for(int i=0;i<11;i++){
		Push(S,i);
	}
	int length = Length(S);
	printf("顺序栈的长度为%d\n",length);
	PrintStack(S);
	printf("\n\n");
	printf("当前栈顶元素为:%d",	GetEle(S));
	
	printf("\n\n");
	int e=0;
	Pop(S,e);
	printf("出栈元素为:%d",e);
	
	printf("\n\n");
	printf("当前栈顶元素为:%d",	GetEle(S));
	
	PrintStack(S);
	printf("\n\n");
	
	DestoryStack(S);
	printf("栈销毁之后:\n"); 
	PrintStack(S);
	printf("\n\n");
	 
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值