两个队列模拟一个栈

#include <iostream>  
#include <assert.h>  
#include <queue>  
using namespace std;  
/*两个队列模拟一个堆栈*/  
/*队列A、B 
入栈:将元素依次压入到非空的队列。第一个元素压倒对列A 
出栈:把队列A的前n-1个元素倒到队列B,把第n个元素去掉。此时数据在B中,下次操作,则对B操作。 
栈顶:把队列A的前n-1个元素倒到队列B,把第n个元素作为栈顶*/  
template <typename T>  
class MyStack  
{  
public:  
    //入栈,第一个元素进到队列deque1。以后每一个元素进到非空的队列  
    void  push(const T &element) ; 
	
    //出栈。将非空队列的前n-1个元素转移到还有一个空的队列。删除非空队列的第n个元素  
    void pop() ; 
	
    //栈顶元素,将非空队列的前n-1个元素转移到还有一个空的队列,将非空队列的第n个元素返回  
    T top();  
	
    //栈是否为空  
    bool empty()  
    {  
        return (q1.empty()&&q2.empty());  
    }  
private:  
    queue<T> q1;  
    queue<T> q2;  
};  

template<typename T> void MyStack<T>::push(const T &element)
{  
	if (q1.empty() && q2.empty())  
	{  
		q1.push(element);  
	}  
	else if (!q1.empty() && q2.empty())  
	{  
		q1.push(element);  
	}  
	else if (q1.empty() && !q2.empty())  
	{  
		q2.push(element);  
	}  
}  
template<typename T>void MyStack<T>::pop()
{  
	if (!q1.empty())  
	{  
		int size = q1.size();  
		for (int i=0; i<size-1; i++)  
		{  
			q2.push(q1.front());  
			q1.pop();  
		}  
		q1.pop();  
	}  
	else  
	{  
		int size = q2.size();  
		for (int i=0; i<size-1; i++)  
		{  
			q1.push(q2.front());  
			q2.pop();  
		}  
		q2.pop();  
	}  
} 
template <typename T>T MyStack<T>::top()
{  
	if (!q1.empty())  
	{  
		int size = q1.size();  
		for (int i=0; i<size-1; i++)  
		{  
			q2.push(q1.front());  
			q1.pop();  
		}  
		T temp = q1.front();  
		q1.pop();  
		q2.push(temp);  
		return temp;  
	}  
	else  
	{  
		int size = q2.size();  
		for (int i=0; i<size-1; i++)  
		{  
			q1.push(q2.front());  
			q2.pop();  
		}  
		T temp = q2.front();  
		q2.pop();  
		q1.push(temp);  
		return temp;  
	}  
}   
int main(int argc, char *argv[])  
{  
    MyStack<int> my;  
    for (int i=0; i<10; i++)  
    {  
        my.push(i);  
    }  
    while (!my.empty())  
    {  
        cout<<my.top()<<" ";  
        my.pop();  
    }  
    cout<<endl;  
	return 0;
}  

原文地址:https://www.cnblogs.com/lcchuguo/p/5223683.html