数据结构--共享栈C++(模板类实现)
作者:
AmbitionX
,
2022-05-04 14:29:15
,
所有人可见
,
阅读 227
#include <iostream>
using namespace std;
const int StackSize = 100;
template <typename DataType>
class BothStack
{
public:
BothStack();
void Push(int i, DataType x);
DataType Pop(int i);
DataType GetTop(int i);
void Empty(int i);
private:
DataType data[StackSize];
int top1, top2;
};
template <typename DataType>
BothStack<DataType>:: BothStack()
{
top1 = -1;
top2 = StackSize;
}
template <typename DataType>
void BothStack<DataType>:: Push(int i, DataType x)
{
if (top1 == top2) throw "上溢";
if (i != 1 && i != 2) throw "输入错误";
if (i == 1) data[++ top1] = x;
if (i == 2) data[-- top2] = x;
}
template <typename DataType>
DataType BothStack<DataType>:: Pop(int i)
{
if (i != 1 && i != 2) throw "输入错误";
if (i == 1)
{
if (top1 == -1) throw "下溢";
return data[top1--];
}
else
{
if (top2 == StackSize) throw "下溢";
return data[top2++];
}
}
template <typename DataType>
DataType BothStack<DataType>:: GetTop(int i)
{
if (i != 1 && i != 2) throw "输入错误";
if (i == 1) return data[top1];
return data[top2];
}
template <typename DataType>
void BothStack<DataType>:: Empty(int i)
{
if (i != 1 && i != 2) throw "输入错误";
if (i == 1)
{
if (top1 == -1) cout << "为空" << endl;
else cout << "不空" << endl;
}
else
{
if (top2 == StackSize) cout << "为空" << endl;
else cout << "不空" << endl;
}
}
int main()
{
BothStack<int> B;
cout << "栈1入栈1 2 栈2入栈3 4";
B.Push(1, 1);
B.Push(1, 2);
B.Push(2, 3);
B.Push(2, 4);
cout << "栈1的栈顶元素位: " << B.GetTop(1) << endl;
cout << "栈1的栈顶元素位: " << B.GetTop(2) << endl;
int x, y;
try
{
x = B.Pop(1);
y = B.Pop(2);
cout << "栈1出来的元素是: " << x << "栈1出来的元素是: " << y << endl;
}
catch (char *str)
{
cout << str << endl;
}
int z, w;
try
{
cout << "请输入栈1的入栈元素: " << endl;
cin >> z;
cout << "请输入栈2的入栈元素: " << endl;
cin >> w;
cout << "1的待入栈元素为: " << z << " 2的待入栈元素为: " << w << endl;
B.Push(1, z);
B.Push(2, w);
}
catch (char *str)
{
cout << str << endl;
}
B.Empty(1);
B.Empty(2);
return 0;
}