leetcode 225. 用队列实现栈


思路:用两个队列,先放到s2中,然后把s1的全部放入s2中,再将s1和s2进行交换即可。

class MyStack {
    Deque s1=new ArrayDeque<>();
    Deque s2=new ArrayDeque<>();

    public MyStack() {

    }
    
    public void push(int x) {
        s2.addLast(x);
        while(!s1.isEmpty()){
            s2.addLast(s1.pollFirst());
        }
        Deque tmp=s1;
        s1=s2;
        s2=tmp;
    }
    
    public int pop() {
        return s1.pollFirst();
    }
    
    public int top() {
        return s1.peekFirst();
    }
    
    public boolean empty() {
        return s1.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();
 */

相关