225. 用队列实现栈 - 力扣(LeetCode) (leetcode-cn.com)
思路:
①坑定使用两个a,b 队列实现栈
②当执行push操作的时候,可以先将要push的元素放入b,让后将a的所有元素依次出队,同时依次入队b,这样就使push 的元素都在队列的首位,
执行完上述操作后,交换a b,保证所有的元素都在a队列里面
③pop 就是a出队列,top就是a的首位元素
class MyStack {
public Queue<Integer>a;
public Queue<Integer>b;
/** Initialize your data structure here. */
public MyStack() {
a=new LinkedList<>();
b=new LinkedList<>();
}
/** Push element x onto stack. */
//始终让a存储数据,b为空,用来调整顺序
public void push(int x) {
Queue tmp=b;
b.offer(x);
while(!a.isEmpty()){
b.offer(a.poll());
}
b=a;
a=tmp;
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return a.poll();
}
/** Get the top element. */
public int top() {
return a.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return a.isEmpty();
}
}
/**
* 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();
* boolean param_4 = obj.empty();
*/