“共享栈”实际代码实现【物联网1132-11】

#include<iostream>
using namespace std;
const int StackSize = 100;            

template<class T>        
class BothStack  
{  
public:  
	 BothStack(){top1=-1;top2=StackSize;}   
	 ~BothStack(){}   
	 void Push(int i,T x);
	 T Pop(int i);
	 T GetTop(int i);
	 int Empty(int i);
private:  
	 T data[StackSize];    
	 int top1,top2; 
};  

template<class T>
void BothStack<T>::Push(int i,T x)
{
	if(top1==top2-1)throw"错误";
	if(i==1)data[++top1]=x;
	if(i==2)data[--top2]=x;
}

template<class T>
T BothStack<T>::Pop(int i)
{
	if(i==1)
	{
		if(top1==-1)throw"错误";
		return data[top1--];
	}
	if(i==2)
	{
		if(top2==StackSize)throw"错误";
		return data[top2++];
	}
}

template<class T>
T BothStack<T>::GetTop(int i)
{
	if(i==1)
	{
		if(top1==-1)throw"错误";
		cout<<"这个元素是:"<<data[top1]<<endl;
	}
	if(i==2)
	{
		if(top2==StackSize)throw"错误";
		cout<<"这个元素是:"<<data[top2]<<endl;
	}
	return 0;
}

template<class T>
int BothStack<T>::Empty(int i)
{
	if(i==1)
	{
		if(top1==-1)
			cout<<"栈1空"<<endl;
		else
			cout<<"栈1 is not 空"<<endl;
	}
	if(i==2)
	{
		if(top2==StackSize)
			cout<<"栈2空"<<endl;
		else
			cout<<"栈2 is not 空"<<endl;
	}
	return 0;
}

int main()
{
	BothStack<int>s1;
	int m;
	do{
	cout<<"-------------------------"<<endl;
	cout<<"输入1开始入栈"<<endl;
	cout<<"输入2开始弹栈"<<endl;
	cout<<"输入3开始读取栈顶"<<endl;
	cout<<"输入4开始判断是否空"<<endl;
	cin>>m;
	switch(m)
	{
		case 1:
			int a;
			double b;
			cout<<"请输入哪个栈和入栈的元素值"<<endl;
			cin>>a>>b;
			s1.Push(a,b);
			break;
		case 2:
			int c;
			cout<<"请输入要取哪个栈的栈顶(出栈)"<<endl;
			cin>>c;
			s1.Pop(c);
			break;
		case 3:
			int v;
			cout<<"请输入要取哪个栈的栈顶(读取值而已)"<<endl;
			cin>>v;			
			s1.GetTop(v);
			break;
		case 4:
			int h;
			cout<<"请输入想判断“哪个栈”为空"<<endl;
			cin>>h;			
			s1.Empty(h);
			break;
	}
	}while(1);
	return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值