[LeetCode] 225. 用队列实现栈

这个 不是很简单嘛。。。。

用一个队列来实现,每次pop和top的时候把数据循环从头部取出尾部输入,就可以得到和栈一样的顺序

class MyStack {

    /** Initialize your data structure here. */
    private Queue<Integer> queue;
    public MyStack() {
        queue=new LinkedList<>();
    }
    
    /** Push element x onto stack. */
    public void push(int x) {
        queue.offer(x);
    }
    
    /** Removes the element on top of the stack and returns that element. */

    private void shift(){
        int size=queue.size();
        for(int i=0;i<size-1;i++){
            queue.offer(queue.poll());
        }
    }

    public int pop() {
        shift();
        return queue.poll();
    }
    
    /** Get the top element. */
    public int top() {
        shift();
        int res=queue.poll();
        queue.offer(res);
        return res;
    }
    
    /** 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/doyi111/p/12676029.html