前端之家收集整理的这篇文章主要介绍了
《数据结构》实验【两栈】,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
#include <iostream>
using namespace std;
const int Max=100;
template <class T>
class BothStack
{
public:
BothStack(){top1=-1;top2=Max;}
~BothStack(){}
void Push(int i,T x);
void Pop(int i);
private:
T data[Max];
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; cout<<data[top1]<<endl;}
if(i==2){data[--top2]=x; cout<<data[top2]<<endl;}
}
template <class T>
void BothStack<T>::Pop(int i)
{
if(i==1)
{
if(top1==-1)throw"下溢";
cout<<data[top1--]<<endl;
}
if(i==2)
{
if(top2==Max)throw"下溢";
cout<<data[top2++]<<endl;
}
}
int main()
{
BothStack<int> one;
cout<<"-----------top1入栈-------------"<<endl;
one.Push(1,80);
one.Push(1,85);
cout<<"-----------top2入栈-------------"<<endl;
one.Push(2,90);
one.Push(2,95);
cout<<"-----------top1出栈-------------"<<endl;
one.Pop(1);
one.Pop(1);
cout<<"-----------top2出栈-------------"<<endl;
one.Pop(2);
one.Pop(2);
return 0;
}
原文链接:https://www.f2er.com/datastructure/382878.html