思路和兩個棧實現隊列一樣。代碼如下:
#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;
}