zoukankan      html  css  js  c++  java
  • LeetCode 232 用栈实现队列

    Leetcode 232 用栈实现队列

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

    • push(x) -- 将一个元素放入队列的尾部。
    • pop() -- 从队列首部移除元素。
    • peek() -- 返回队列首部的元素。
    • empty() -- 返回队列是否为空。

    辅助栈/双栈

    • 输入栈(负责接收输入add())
    • 输出栈(负责调整顺序并输出peek()、pop())

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

    class MyQueue {
        private List<Integer> listIn;
        private List<Integer> listOut;
    
        /** Initialize your data structure here. */
        public MyQueue() {
            //初始化
            this.listIn = new ArrayList<>();
            this.listOut = new ArrayList<>();
        }
        
        /** Push element x to the back of queue. */
        public void push(int x) {
            listIn.add(x);
        }
        
        /** Removes the element from in front of queue and returns that element. */
        public int pop() {
            int peekElem = peek();
            listOut.remove(listOut.size()-1);
            return peekElem;
        }
        
        /** Get the front element. */
        public int peek() {
            /*转移元素到listOut*/
            if(listOut.isEmpty()) {
                for(int idx=listIn.size()-1; idx>=0; idx--) {
                    listOut.add(listIn.get(idx));
                }
                listIn.clear();
            }
    
            int peekElem = listOut.get(listOut.size()-1);
            return peekElem;
        }
        
        /** Returns whether the queue is empty. */
        public boolean empty() {
            return listIn.isEmpty() && listOut.isEmpty();
        }
    }
    
  • 相关阅读:
    写诊股广告页面遇到的问题
    移动端web页面滚动不流畅,卡顿闪烁解决方案
    用JS和JQ来获取子节点!
    CSS样式表的写作规范
    常用css3
    移动端引用echarts的折线图
    JS----获取DOM元素的方法(8种)
    随机对决
    字体
    Echarts个性化图表的样式--绘制南丁格尔图
  • 原文地址:https://www.cnblogs.com/CodeSPA/p/13566881.html
Copyright © 2011-2022 走看看