一、题目
二、思路
队列特点:先进先出;
栈特点:先进后出。
题目给出2个队列,为了让队列实现栈的“先进后出”:
(1)在主队列中进入元素前,可以将主队列中的元素出队,进入辅助队列中(暂存着),
(2)然后将主队列进入新元素后;
(3)辅助队列中暂存的元素重新回到主队列中。
三、代码
class MyStack { public: queue<int> q1; queue<int> q2; MyStack() { } void push(int x) { while(!q1.empty()){ q2.push(q1.front()); q1.pop(); } q1.push(x); while(!q2.empty()){ q1.push(q2.front()); q2.pop(); } } int pop() { int a = q1.front(); q1.pop(); return a; } int top() { return q1.front(); } bool empty() { return q1.empty(); } }; /** * Your MyStack object will be instantiated and called as such: * MyStack* obj = new MyStack(); * obj->push(x); * int param_2 = obj->pop(); * int param_3 = obj->top(); * bool param_4 = obj->empty(); */