用两个栈实现队列

题目是就用两个栈来实现队列....

思路还是比较清晰的,所以直接上代码.......

//用两个栈实现队列
#include<iostream>
#include<stack>
using namespace std;
template <typename T> class MyQueue{
public:
	MyQueue(){};
	T pop();
	void push(T);
	bool empty();
private:
	stack<T> stack1;    //用于入队和入队
	stack<T> stack2;	//用于出队
};
template<typename T> T MyQueue<T>::pop(){        //出队
	T temp;
	if(!stack2.empty()){temp=stack2.top();stack2.pop();}
	else{
		if(stack1.empty()) {cout<<"error"<<endl;return 0;}
		else{
			while(!stack1.empty()){
				stack2.push(stack1.top());
				stack1.pop();
			}
			temp=stack2.top();
			stack2.pop();
		}
	}
	return temp;
}
template<typename T> void MyQueue<T>::push(T t){ //入队
	stack1.push(t);
	return;
}
template<typename T> bool MyQueue<T>::empty(){
	/*if(stack1.empty()&&stack2.empty()) return true;
	else return false;*/
	return stack1.empty()&&stack2.empty()?true:false;
}
void test(MyQueue<int> q){               //测试
	int data[]={1,2,3,4,5,6,7,8,9,10};
	for(int i=0;i<=6;i++)
		q.push(data[i]);
	for(int i=0;i<=5;i++)
		cout<<q.pop()<<" ";
	cout<<endl;
	for(int i=7;i<=9;i++)
		q.push(data[i]);
	while(!q.empty()){
		cout<<q.pop()<<" ";
	}
	cout<<endl;
	return;
}
int main(void){
	MyQueue<int> q;
	test(q);
	system("pause");
	return 0;
}
原文地址:https://www.cnblogs.com/aLittleBitCool/p/1958399.html