现在的位置: 首页 > 综合 > 正文

两个队列模拟一个栈

2013年12月09日 ⁄ 综合 ⁄ 共 1005字 ⁄ 字号 评论关闭
#include <iostream>
#include <queue>
#include <assert.h>
using namespace std;

template <typename T>
class MyStack
{
	public:
		void push(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);
		}

		void 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();
			}
		}

		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();
				}
				q2.pop();
				T temp=q2.front();
				q2.pop();
				q1.push(temp);
				return temp;
			}

		}

		bool empty()
		{
			return (q1.empty() && q2.empty());
		}
	private:
		queue<T> q1;
		queue<T> q2;
};

void main()
{
	MyStack<int> my;
	for(int i=0; i<10; i++)
		my.push(i);
	while(!my.empty())
	{
		cout<<my.top()<<" ";
		my.pop();

	}
	cout<<endl;
}

参考http://blog.csdn.net/wangyangkobe/article/details/5910362

抱歉!评论已关闭.