两栈共享空间的实现

两栈共享空间:

利用一个数组来存储两个栈;让一个栈底为数组的首端;一个栈底为数组的末端.每个栈都向数组中间延伸,以此来充分利用数组的空间.

两个"指针",一个数组就可以将他实现.

实现代码:

<strong>#include<iostream>
using namespace std;
const  int smax=50;
template <class Datatype>
class Bothsteck
{
	public:
		Bothsteck(){top1=-1;top2=smax;}
		~Bothsteck(){}
		void Set(Datatype a[],int n,Datatype b[],int m);//1先建立一个基础双栈,为后续操作做准备
		void Push(Datatype x,int i);//入栈.i为第几个栈.栈一就用top1操作.否则
		void Pop(int i);//出栈i
		Datatype Get(int i);//取出栈i顶元素
		int Empty(int i);//判断栈i是否为空?
        
    private:
		int top1;
		int top2;
		Datatype data[smax];
		
};
template <class Datatype>
void Bothsteck<Datatype>::Set(Datatype a[],int n,Datatype b[],int m)//1先建立一个基础双栈,为后续操作做准备
{
	if (top1==top2-1)throw;//"上溢和下溢"
    {for (int i=0;i<n;i++)
		data[++top1]=a[i];
	for(int t=0;t<m;t++)
        data[--top2]=b[t];
	}
	cout<<"基础双栈建好"<<endl;
}
template <class Datatype>
void Bothsteck<Datatype>::Push(Datatype x,int i)//入栈.
{
	if(top1==top2-1)throw;
	if(i==1){data[++top1]=x; cout<<x<<"入栈1成功"<<endl;}
	if(i==2){data[--top2]=x; cout<<x<<"入栈2成功"<<endl;}
}
template <class Datatype>
void Bothsteck<Datatype>::Pop(int i)//出栈
{
	if(i==1)
	{if(top1==-1)throw;
	 cout<<"出栈1结果:  "<<data[top1--]<<endl;
	}
	if(i==2)
	{if(top2==smax)throw;
	 cout<<"出栈2结果:  "<<data[top2++]<<endl;  
	}
}
template <class Datatype>
Datatype Bothsteck<Datatype>::Get(int i)//取出栈i顶元素
{
   
   if(i==1)
	{if(top1==-1)throw;
	 return data[top1];
	}
   if(i==2)
	{if(top2==smax)throw;
	 return data[top2];  
	}
}
template<class Datatype>
int Bothsteck<Datatype>::Empty(int i)//判断栈i是否为空?
{
  if(i==1)
  {return top1==-1? 0:1;}
  if(i==2)
  {return top2==smax?0:1;}
}
int main()
{
	
	int n=3;int m=3;int a[smax],b[smax];
	cout<<"请输入"<<n<<"个数为建立栈1做准备:";
	for(int i=0;i<n;i++)
		cin>>a[i];
    cout<<"请输入"<<m<<"个数为建立栈2做准备:";
	for(int t=0;t<m;t++)
		cin>>b[t];
	Bothsteck<int> s;
	 s.Set(a,n,b,m);//1先建立一个基础双栈

	 cout<<"1->入栈1||2->入栈2:   "<<"输入一个入栈元素    ";
	 int i2;
	 int t2; 
	 cin>>i2>>t2;
     s.Push(t2,i2);//入栈.

     cout<<"1->出栈1||2->出栈2:   ";
      cin>>i2;
	s.Pop(i2);//出栈i

	cout<<"1->取栈1顶元素||2->取栈2顶元素:   ";
      cin>>i2;
	cout<<"取出栈顶元素  "<<s.Get(i2)<<endl;//取出栈i顶元素

    cout<<"1->判断栈1是否为空||2->判断栈2是否为空:   ";
      cin>>i2;
	 cout<<"0为空,1为非空:    "<<s.Empty(i2)<<endl;//判断栈i是否为空?
	 return 0;
}</strong>

调试结果:


总结:

双栈的实现比单栈要麻烦一点,他要将两个后进先出的栈都要考虑到,但他可以同时利用两个栈,充分的利用了一个数组开辟的空间;要是三个栈,四个栈就更麻烦了,使问题及代码更复杂.对于较复杂代码的实现,要更加的细心!!!



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值