225. 用队列实现栈 - 力扣(LeetCode) (leetcode-cn.com)https://leetcode-cn.com/problems/implement-stack-using-queues/用一个队列就可以,pop的时候把队列里除了最后一个之外的所有元素重新加入队列,再poll()就好了。
class MyStack {
Queue<Integer> q;
public MyStack() {
q = new LinkedList<Integer>();
}
public void push(int x) {
q.add(x);
}
public int pop() {
int size = q.size();
for (int i=0;i<q.size()-1;i++){
q.add(q.poll());
}
return q.poll();
}
public int top() {
int t = this.pop();
this.push(t);
return t;
}
public boolean empty() {
return q.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();
*/