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

该博客介绍了如何使用一个数组来创建两个栈,分别利用数组的奇数和偶数索引来存储两个栈的数据。栈的满状态定义为两个栈的栈顶元素达到数组的倒数第二个和倒数第一个位置。代码示例展示了栈的插入(Push)和删除(Pop)操作,并提供了检查栈是否为空(Isempty)和是否已满(Isfull)的辅助函数。虽然这种方法节省了空间,但其复杂性不如直接使用数组创建一个栈。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用一个数组创建两个栈(方法三)

基本思路:将数组的第一、二个单元作为两个栈的栈底,一个栈使用奇数单元,一个栈使用偶数单元,当两个栈的栈顶都触顶时就认为栈满了,说实话这种方法实现还不如直接用数组创建一个栈。
整体代码:

#include<iostream>          //这个程序只考虑了长度为偶数的情况
const int stacksize=10;
typedef struct Stack{
	int data[stacksize];
	int top1=0;
	int top2=1;
}Stack;
using namespace std;
int Isempty(Stack*);
int Isfull(Stack*);
int Push(Stack*,int,int);
int Pop(Stack*);
int main(void){
	Stack p;
	int choice,x;
	while(!Isfull(&p)){
		cout<<"请输入你要存入的数据"<<endl;
		cin>>x;
		cout<<"请选择存入栈一还是栈二"<<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==0&&p->top2==1;
}
int Isfull(Stack* p){
	return p->top1==stacksize-2&&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->top2<stacksize-2){
		p->top1+=2;
		p->data[p->top1]=x;
	}else if(choice==2&&p->top2<stacksize-1){
		p->top2+=2;
		p->data[p->top2]=x;
	}else return 0;
	return 1;
}
int Pop(Stack* p){
	if(Isempty(p)){
		cout<<"The stack is empty"<<endl;
		exit(0);
	}
	int x=0;
	if(p->top1>0){
		x=p->data[p->top1];
		p->top1-=2;
	}else{
		x=p->data[p->top2];
		p->top2-=2;
	}
	return x;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值