您的位置:首页 > 大数据 > 物联网

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

2014-10-30 23:25 316 查看
#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;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐