两栈用一个空间

#include <iostream>
using namespace std;

const int MAX_SIZE = 100;

template<class DataType>
class BothStack {
private:
	DataType *data;
	int top1,top2;
	int size;
public:
	BothStack();
	BothStack(int len);
	~BothStack();
	void push(int num,DataType ch);
	DataType pop(int num);
	DataType getTop(int num);
	bool isEmpty(int num);
	bool isFull();
	void setNull();
	class Full{};
	class Empty{};
};

template<class DataType>
BothStack<DataType>::BothStack() {
	data = new DataType[MAX_SIZE];
	size = MAX_SIZE;
	top1 = -1;
	top2 = MAX_SIZE;
}

template<class DataType>
BothStack<DataType>::BothStack(int len) {
	data = new DataType[len];
	size = len;
	top1 = -1;
	top2 = len;
}

template<class DataType>
BothStack<DataType>::~BothStack() {
	delete [] data;
}

template<class DataType>
void BothStack<DataType>::push(int num, DataType ch) {
	if (isFull()) {
		throw BothStack<DataType>::Full();
	} else if (num == 1) {
		data[++top1] = ch;
	} else if (num == 2) {
		data[--top2] = ch;
	}
}

template<class DataType>
DataType BothStack<DataType>::pop(int num) {
	if (isEmpty(num)) {
		throw BothStack<DataType>::Empty();
	} else if (num == 1){
		return data[top1--];
	} else if (num == 2){
		return data[top2++];
	}
	return -1;
}

template<class DataType>
DataType BothStack<DataType>::getTop(int num) {
	if (isEmpty(num)) {
		throw BothStack<DataType>::Empty();
	} else if (num == 1){
		return data[top1];
	} else if (num == 2){
		return data[top2];
	}
	return -1;
}

template<class DataType>
bool BothStack<DataType>::isEmpty(int num) {
	return (num == 1) ? (top1 == -1) : (top2 == size);
}

template<class DataType>
bool BothStack<DataType>::isFull() {
	return top1 + 1 == top2;
}

template<class DataType>
void BothStack<DataType>::setNull() {
	top1 = -1;
	top2 = size;
}

int main()
{
	try {
		
		BothStack<int> b(3);
		b.push(1, 100);
		b.push(1, 200);
		b.push(2, 300);
		//b.push(2, 400);
		cout << b.pop(1) << endl;
		cout << b.pop(1) << endl;
		cout << b.pop(2) << endl;
		
	} catch(BothStack<int>::Full) {
		
		cout << "BothStack<int>::Full" << endl;
		
	}
	
    return 0;
}

posted on 2022-04-02 21:14  历史锅巴  阅读(43)  评论(0)    收藏  举报