学习随记二十三——使用一个数组建立两个栈(方法二)

使用一个数组建立两个栈(方法二)

基本思路;两个栈顶从中间分别向两边扩展,当触碰到了两边的边界就认为栈满了,我觉得我使用的第一种用一个数组创建两个栈的方法比这个要好,从两边向中间扩展对资源的利用更好且更灵活。
问题;我刚开始在写的时候没有充分考虑到数组越界的问题,经过后面的调试发现的,以后在使用数组时多考虑。
整体代码:

#include<iostream>
const int stacksize=10;
typedef struct Stack{
	int data[stacksize];
	int top1=stacksize/2-1;
	int top2=stacksize/2;
}Stack;
using namespace std;
int Isempty(Stack*);        //判栈空
int Isfull(Stack*);         //判栈满
int Push(Stack*,int,int);   //入栈
int Pop(Stack*);            //出栈
int main(void){
	Stack s;
	int x,choice,i=0;
	while(!Isfull(&s)/*i<stacksize-2*/){
		cout<<"输入一个数字"<<endl;
		cin>>x;
		cout<<"请选择第一个栈还是第二个栈"<<endl;
		cin>>choice;
		Push(&s,x,choice);
		i++;
	}
	while(!Isempty(&s)){
		x=Pop(&s);
		cout<<x<<endl;
	}
	return 0;
}
int Isempty(Stack* p){
	return p->top1>=stacksize/2-1&&p->top2<=stacksize/2;
}
int Isfull(Stack* p){
	return p->top1==0&&p->top2==stacksize-1;
}
int Push(Stack* p,int x,int choice){
	if(Isfull(p)){
		cout<<"The stack is full"<<endl;
		exit(0);
	}
	if(choice==1&&p->top1>0){
		p->data[--p->top1]=x;
	}else if(choice==2&&p->top2<stacksize-1){
		p->data[++p->top2]=x;
	}else return 0;
	return 1;
}
int Pop(Stack* p){
	if(Isempty(p)){
		cout<<"The stack is empty"<<endl;
		return 0;
	}
	int x;
	if(p->top1<stacksize/2-1){
		x=p->data[p->top1++];
	}else{
		x=p->data[p->top2--];
	}
	return x;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值