用兩個隊列實現一個棧

思路和兩個棧實現隊列一樣。代碼如下:

#include<iostream>
#include<queue>

using namespace std;

class solution
{
public:
	void push(int x)
	{
		q1.push(x);
	}
	int pop()
	{

		if (q2.empty())
		{
			while (!q1.empty())
			{
				q2.push(q1.front());
				q1.pop();
			}
		}
		int front = q2.front();
		q2.pop();
		return front;
	}
private:
	queue<int> q1;
	queue<int> q2;
};
int main()
{
	solution queue;
	queue.push(3);
	queue.push(-3);
	cout << queue.pop() << endl;
	queue.push(9);
	cout << queue.pop() << endl;
	cout << queue.pop() << endl;
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章