C++两个队列实现一个栈

C++两个队列实现一个栈

/*
 * source.cpp
 *
 *  Created on: 2015年6月21日
 *      Author: codekiller
 */

#include "iostream"
#include "queue"
#include <exception>
#include "stdexcept"
using namespace std;

#define  should_not_reach_here



template <typename T> class QStack{

	public:
		QStack(void){};
		~QStack(void){};
		void push(const T& element);
		T pop();
	private:
		queue<T> queue1;
		queue<T> queue2;

};

template <typename T> void QStack<T>::push(const T& element){

	if(!queue2.empty())
	queue2.push(element);
	else if(!queue1.empty())
		queue1.push(element);
	else if(queue1.empty()&&queue2.empty())
		queue1.push(element);

}

template <typename T> T QStack<T>::pop(){
	if(queue1.size()==0&&queue2.size()==0)
	{	throw underflow_error(string("QStack UnderFlow"));
	//return 0;
	}
	if(queue1.size()==0){
		while(queue2.size()>1){
			queue1.push(queue2.front());
			queue2.pop();
		}
		T & dataout=queue2.front();
		queue2.pop();
	    return dataout;
	}else if(queue2.size()==0){
		while(queue1.size()>1){
			queue2.push(queue1.front());
			queue1.pop();
		}
		T & dataout=queue1.front();
		queue1.pop();
		return dataout;
	}

	should_not_reach_here
}

int main(){

	QStack<int> sstack;
	sstack.push(1);
	cout<<sstack.pop()<<endl;
	sstack.push(100);
try{
	cout<<sstack.pop()<<endl;
	cout<<sstack.pop()<<endl;
	cout<<sstack.pop()<<endl;
}
catch(underflow_error &err){
	cerr<<err.what()<<endl;
}

}




 

posted @ 2015-06-21 22:03  一杯半盏  阅读(408)  评论(0编辑  收藏  举报