学习随记二十二——用一个数组实现两个栈(方法一)

用一个数组实现两个栈(方法一)

基本思路:两个栈的栈底分别在两头,栈顶向中间趋近当栈顶相遇时即说明栈满

整体代码;

#include<iostream>
const int stacksize=10;
typedef struct Stack {
	int data[stacksize];
	int top1=-1;
	int top2=stacksize;
}Stack;
using namespace std;
int Isempty(Stack*);        //判栈空
int Isfull(Stack*);         //判栈满
int Push(Stack*,int,int);   //入栈
int Pop(Stack*);            //出栈
int main(void){
	Stack p;
	int x,choice;
	while(!Isfull(&p)){
		cout<<"Please input a number."<<endl;
		cin>>x;
		cout<<"Do you choice one or two?"<<endl;
		cin>>choice;
		Push(&p,x,choice);
	}
 while(!Isempty(&p)){
		x=Pop(&p);
		cout<<x<<endl;
	}
	return 0;
}
int Isempty(Stack* p){
	return p->top1==-1&&p->top2==stacksize;
}
int Isfull(Stack* p){
	return p->top1+1==p->top2;
}
int Push(Stack* p,int x,int choice){
	if(Isfull(p)){
		cout<<"The stack is full."<<endl;
		return 0;
	}
	if(choice==1)	p->data[++p->top1]=x;
	else if(choice==2) 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;
	}
	if(p->top1>=0){
		return p->data[p->top1--];
	}else{
		return p->data[p->top2++];
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值