225. 用队列实现栈


225. 用队列实现栈

    Queue<Integer> queue;

    /** Initialize your data structure here. */
    public MyStack() &#123;
        queue = new LinkedList<Integer>();
    &#125;

    /** Push element x onto stack. */
    public void push(int x) &#123;
        int n = queue.size();
        queue.offer(x);
        for (int i = 0; i < n; i++) &#123;
            queue.offer(queue.poll());///头出尾进
        &#125;
    &#125;

    /** Removes the element on top of the stack and returns that element. */
    public int pop() &#123;
        return queue.poll();
    &#125;

    /** Get the top element. */
    public int top() &#123;
        return queue.peek();
    &#125;

    /** Returns whether the stack is empty. */
    public boolean empty() &#123;
        return queue.isEmpty();
    &#125;

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/implement-stack-using-queues/solution/yong-dui-lie-shi-xian-zhan-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

文章作者:   future
版权声明:   本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 future !
  目录