双栈(Dual Stack)c++实现

某程序需要两个栈s1、s2,但任何时候s1、s2存储的元素总数不超过2MAX,但某些时候s1或s2储存的元素个数会超过MAX。

对于双栈,可以采用同一个内存空间,通过首指针和尾指针分别作为两个栈的顶指针,从而实现双栈。

双栈最大的好处是内存利用率高,灵活性强。

但也有运算复杂、长度固定等缺点。

#include<iostream>
using namespace std;
template <class T>
class DualStack
{
	private:
		int top1,top2;
		T * data;
		int allMaxsize;
	public:
		DualStack(int sz);
		~DualStack(){
			delete []data;
		};
		bool full();
		bool empty1();
		bool empty2();
		int size1();
		int size2();
		int push1(T x);
		int push2(T x);
		T pop1();
		T pop2();
		
} ;
template<class T>
DualStack<T>::DualStack(int sz)
{
	allMaxsize=2*sz;
	data=new T[allMaxsize];
	top1=-1;
	top2=allMaxsize;
}
template<class T>
bool DualStack<T>::full()
{
	return top1+1==top2;
}
template<class T>
bool DualStack<T>::empty1()
{
	return  top1==-1;
}
template<class T>
bool DualStack<T>::empty2()
{
	return top2==allMaxsize;
}
template<class T>
int DualStack<T>::size1()
{
	return top1+1;
 } 
template<class T>
int DualStack<T>::size2()
{
	return allMaxsize-top2;
}
template<class T>
int DualStack<T>::push1(T x)
{
	if(full())return 0;
	data[++top1]=x;
	return 1;
}
template<class T>
int DualStack<T>::push2(T x)
{
	if(full())return 0;
	data[--top2]=x;
	return 1;
}
template<class T>
T DualStack<T>::pop1()
{
	return data[top1--];
}
template<class T>
T DualStack<T>::pop2()
{
	return data[top2++];
}
int main()
{
	DualStack<int> a(30);
	for(int i=1;i<15;i++){
		a.push1(i);
		a.push2(i);
	}
	for(int i=1;i<15;i++){
		cout<<a.pop1()<<' '<<a.pop2()<<endl;
	}
}

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值