Method 1
使用两个队列:一个主队列,一个辅助队列
首先将元素入队q2,然后将q1的元素全部出队,再入队到q2.再将q1和q2互换,则q1中的元素即为栈内元素
AC Code
class MyStack {
public:queue<int> q1;queue<int> q2;MyStack() {}void push(int x) {q2.push(x);while(!q1.empty()){q2.push(q1.front());q1.pop();}swap(q1, q2);}int pop() {int x = q1.front();q1.pop();return x;}int top() {return q1.front();}bool empty() {return q1.empty();}
};
Method 2
使用1个队列:
入栈时,首先将元素入队列,然后将新元素之前的所有元素依次出队并入队到队列
AC Code
class MyStack {
public:queue<int> q;MyStack() {}void push(int x) {int n = q.size();q.push(x);while(n-- > 0){q.push(q.front());q.pop();}}int pop() {int x = q.front();q.pop();return x;}int top() {return q.front();}bool empty() {return q.empty();}
};