理论部分
理论来源:b站up主:跟懒猫老师快乐数据结构
C++代码
#include<iostream>
using namespace std;
const int STACKSIZE = 6;
//两栈共享存储空间编程
//使用类模板编程
template<class DataType>
class BothStack
{
private:
DataType *data;//属性,顺序栈,数组
int top1, top2;//属性,top1指向栈1的栈顶,top2指向栈2的栈顶
int capacity;//属性,栈的容量
public:
BothStack();//无参构造函数
BothStack(int size);//有参构造函数
~BothStack();//析构函数
DataType getTop(int num);//弹出栈顶元素,num表明对栈1操作,还是对栈2操作
DataType Pop(int num);//出栈
void Push(int num, DataType elem);//入栈
bool isFull();//判断栈满
bool isEmpty(int num);//判断栈空
class IndexError{};//定义内部异常类
class Empty{};
class Full{};
};
template<class DataType>
BothStack<DataType>::BothStack()
{
data = new DataType[STACKSIZE];
top1 = -1;
top2 = STACKSIZE;
capacity = STACKSIZE;
}
template<class DataType>
BothStack<DataType>::BothStack(int size)
{
data = new DataType[size];
top1 = -1;
top2 = size;
capacity = size;
}
template<class DataType>
BothStack<DataType>::~BothStack()
{
delete[] data;
}
template<class DataType>
DataType BothStack<DataType>::getTop(int num)
{
if (num == 1)
{
//对栈1进行操作
if (isEmpty(num))
{
throw Empty();
}
else
{
return data[top1];
}
}
else if (num == 2)
{
//对栈2进行操作
if (isEmpty(num))
{
throw Empty();
}
else
{
return data[top2];
}
}
else
{
throw IndexError();
}
}
template<class DataType>
DataType BothStack<DataType>::Pop(int num)
{
if (num == 1)
{
//对栈1进行操作
if (isEmpty(num))
{
throw Empty();
}
else
{
return data[top1--];
}
}
else if (num == 2)
{
//对栈2进行操作
if (isEmpty(num))
{
throw Empty();
}
else
{
return data[top2++];
}
}
else
{
throw IndexError();
}
}
template<class DataType>
void BothStack<DataType>::Push(int num, DataType elem)
{
if (isFull())
{
throw Full();
}
else {
if (num == 1)
{
data[++top1] = elem;
}
else if (num == 2)
{
data[--top2] = elem;
}
else {
throw IndexError();
}
}
}
template<class DataType>
bool BothStack<DataType>::isFull()
{
if (top2 == top1 +1)
{
return true;
}
return false;
}
template<class DataType>
bool BothStack<DataType>::isEmpty(int num)
{
if (num == 1)
{
if (top1 == -1)
{
return true;
}
return false;
}
else if (num == 2)
{
if (top2 == capacity)
{
return true;
}
return false;
}
else
{
throw IndexError();
}
}
int main()
{
BothStack<char> bs1;
//栈1中依次压入'a','b','c'
//栈2中依次压入'z','x','y'
//栈3中压入'z',抛出异常
//try--catch捕获异常对象
try {
bs1.Push(1, 'a');
bs1.Push(1, 'b');
bs1.Push(1, 'c');
bs1.Push(2, 'z');
bs1.Push(2, 'y');
bs1.Push(2, 'x');
bs1.Push(2, 'w');
}
catch (BothStack<char>::Full)
{
cout << "Stack Full!!!" << endl;
}
catch (BothStack<char>::IndexError)
{
cout << "Index Error!!!" << endl;
}
try {
cout << bs1.Pop(1) << endl;
cout << bs1.Pop(1) << endl;
cout << bs1.Pop(1) << endl;
cout << bs1.Pop(2) << endl;
cout << bs1.Pop(2) << endl;
cout<<bs1.Pop(2)<<endl;
cout << bs1.Pop(2) << endl;
}
catch (BothStack<char>::Empty)
{
cout << "Stack Empty!!!"<< endl;
}
catch (BothStack<char>::IndexError)
{
cout << "Index Error!!!" << endl;
}
}
运行结果
栈的大小为6