LeetCode 225 用队列实现栈

LeetCode 225 用队列实现栈

问题描述:
使用队列实现栈的下列操作:

  • push(x) -- 元素 x 入栈
  • pop() -- 移除栈顶元素
  • top() -- 获取栈顶元素
  • empty() -- 返回栈是否为空

执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户
内存消耗:37.3 MB, 在所有 Java 提交中击败了61.41%的用户

class MyStack {
    private Deque<Integer> queue;

    /** Initialize your data structure here. */
    public MyStack() {
        this.queue = new LinkedList<Integer>();  //只存储栈顶值
    }
    
    /** 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. */
    public int pop() {
        /*O(N)*/
        int size = queue.size();
        while(size>1) {
            size--;
            queue.offer(queue.poll());
        }
        int topElem = queue.poll();
        return topElem;
    }
    
    /** Get the top element. */
    public int top() {
        int topElem = pop();
        queue.offer(topElem);

        return topElem;
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
        return queue.isEmpty();
    }
}
posted @ 2020-08-26 19:19  CodeSPA  阅读(101)  评论(0编辑  收藏  举报