顺序栈基本功能

目录

1.顺序栈类型定义

2.初始化顺序栈

3.入栈

4.出栈

5.遍历输出栈内所有元素

6.查看栈顶元素

7.完整代码


1.顺序栈类型定义

typedef struct {
	int elem[MAXSIZE];
	int top;
}SqStack;

2.初始化顺序栈

void InitStack(SqStack &S){ //初始化 
	S.top=0; //代表栈空 
}

3.入栈

bool Push(SqStack &S,int x){ //入栈 
	if(S.top>=MAXSIZE)
		return false;
	S.elem[++S.top]=x;
	return true;
}

4.出栈

bool Pop(SqStack &S,int &x){ //出栈 
	if(S.top==0)
		return false;
	x=S.elem[S.top--];
	return true;
}

5.遍历输出栈内所有元素

void PrintStack(SqStack S){ //遍历 
	for(int i=S.top;i>0;i--)
		printf("%3d",S.elem[i]);
	printf("\n");
}

6.查看栈顶元素

bool Top(SqStack S,int &x){ //查看栈顶元素 
	if(S.top==0)
		return false;
	x=S.elem[S.top];
	return true;
}

7.完整代码

#include <stdio.h>

#define MAXSIZE 50

typedef struct {
	int elem[MAXSIZE];
	int top;
}SqStack;

void InitStack(SqStack &S){ //初始化 
	S.top=0; //代表栈空 
}

bool Push(SqStack &S,int x){ //入栈 
	if(S.top>=MAXSIZE)
		return false;
	S.elem[++S.top]=x;
	return true;
}

bool Pop(SqStack &S,int &x){ //出栈 
	if(S.top==0)
		return false;
	x=S.elem[S.top--];
	return true;	
}

void PrintStack(SqStack S){ //遍历 
	for(int i=S.top;i>0;i--)
		printf("%3d",S.elem[i]);
	printf("\n");
}

bool Top(SqStack S,int &x){ //查看栈顶元素 
	if(S.top==0)
		return false;
	x=S.elem[S.top];
	return true;
}

int main(){
	SqStack S;
	int x;
	InitStack(S);
	for(;;){
		scanf("%d",&x);
		if(x==-1)
			break;
		Push(S,x);
	}
	PrintStack(S);
	Pop(S,x);
	printf("出栈元素:%d\n",x);
	PrintStack(S);
	Top(S,x);
	printf("栈顶元素:%d\n",x);
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值