zoukankan      html  css  js  c++  java
  • 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();
        }
    }
    
  • 相关阅读:
    记一次测试服务器被黑
    那些H5用到的技术(5)——视差滚动效果
    POJ1179 Polygon
    Cookies
    SGU167 I-country
    POJ1704
    POJ3233 Matrix Power Series
    TYVJ2002 扑克牌
    Tyvj1933绿豆蛙的归宿
    支配树学习笔记
  • 原文地址:https://www.cnblogs.com/CodeSPA/p/13567128.html
Copyright © 2011-2022 走看看