LeetCode 225. 用队列实现栈

class MyStack {
    //定义一个队列
    Queue<Integer> queue = new LinkedList<>();
    /** Initialize your data structure here. */
    public MyStack() {

    }
    
    /** Push element x onto stack. */
    //队列是先进先出,栈为先进后出,用队列模拟栈时,添加一个元素是在队列的末尾,弹出一个元素是在队头
    //此时把该元素前面的元素全部出队,该元素就到了队首,其余元素再进队,即为一个栈先进后出的顺序
    public void push(int x) {
        queue.add(x);
        int count = queue.size();
        while(count > 1){
            queue.add(queue.remove());
            count--;
        }
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        return queue.remove();
    }
    
    /** Get the top element. */
    public int top() {
        return queue.peek();
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
        return queue.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();
 */
原文地址:https://www.cnblogs.com/peanut-zh/p/13890980.html