双端堆栈
声明:图片及内容基于https://www.bilibili.com/video/av92597456
原理
双栈共享从分别从两端插如数据,向两端删除数据,两站共享实现节省空间
着重理解其编程理念
具体实现
#include<iostream>
using namespace std;
const int STACK_SIZE = 100;
template<class T>
class BothStack {
private:
T* data;
int top1, top2; //两个栈的头
int size;
public:
BothStack();
BothStack(int s); //有参构造
~BothStack(); //析构
void push(int num, T x); //插入:num=1代表栈1,num=2代表栈2
T pop(int num); //弹栈
T getTop(int num); //弹出栈头元素
bool isEmpty(int num); //判断是否为空
bool isFull(); //判断是否满
class Empty1{}; //类内声明异常类
class Empty2{};
class Full{};
};
template <class T>
BothStack<T>::BothStack() {
size = STACK_SIZE;
data = new T[size];
top1 = -1;
top2 = size;
}
template <class T>
BothStack<T>::BothStack(int s) {
size = s;
data = new T[size];
top1 = -1;
top2 = size;
}
template <class T>
BothStack<T>::~BothStack() {
delete[] data;
}
template <class T>
void BothStack<T>::push(int num, T x){
if (isFull()) throw BothStack<T>::Full(); //注意抛出匿名对象
switch (num) {
case 1:
data[++top1] = x; //注意
break;
case 2:
data[--top2] = x; //注意
default:
break;
}
}
template<class T>
T BothStack<T>::pop(int num) {
switch (num) {
case 1:
if (isEmpty(num)) throw BothStack<T>::Empty1();
else {
return data[top1--]; //注意
break;
}
case 2:
if (isEmpty(num)) throw BothStack<T>::Empty2();
else {
return data[top2++]; //注意
break;
}
default:
break;
}
}
template<class T>
T BothStack<T>::getTop(int num) {
if (isEmpty(num)) {
switch (num) {
case 1:
throw BothStack<T>::Empty1();
case 2:
throw BothStack<T>::Empty2();
}
}
else {
switch (num) {
case 1:
return data[top1];
case 2:
return data[top2];
default:
break;
}
}
}
template<class T>
bool BothStack<T>::isEmpty(int num) {
switch (num)
{
case 1:
if (top1 == -1) return true;
else return false;
case 2:
if (top2 == size) return true;
else return false;
default:
break;
}
}
template<class T>
bool BothStack<T>::isFull() {
if (top1 + 1 == top2) return true;
else return false;
}
int main() {
BothStack<int> stack(2);
try {
//stack.pop(1);
//stack.pop(2);
stack.push(2, 1);
stack.push(2, 2);
cout << stack.pop(2)<<endl;
cout << stack.pop(2)<<endl;
}
catch (BothStack<int>::Full) {
cout << "full"<<endl;
}
catch (BothStack<int>::Empty1) {
cout << "empty1"<<endl;
}
catch (BothStack<int>::Empty2) {
cout << "empty2"<<endl;
}
return 0;
}