• 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();
        }
    }
    
  • 相关阅读:
    【javascript】select操作实例
    【javascript】函数
    【javascript】一些资料
    【javascript】操作符:一元操作符
    动态执行Sql
    索引( index )
    事务
    用户相关
    视图(view)
    函数(function)
  • 原文地址:https://www.cnblogs.com/CodeSPA/p/13567128.html
Copyright © 2020-2023  润新知