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();
        }
    }
    
  • 相关阅读:
    Spring Boot启用Swagger2
    Springboot 注解最全详解
    spring-boot-starter-data-jpa 解析
    springboot 微信支付
    springboot整合PageHelper
    SpringBoot配置HTTPS,并实现HTTP访问自动转HTTPS访问
    Springboot 发送短信验证码
    Java volatile关键字的作用
    Android兼容性测试应该怎么做逼格更高呢?
    hadoop日志【2】
  • 原文地址:https://www.cnblogs.com/CodeSPA/p/13566881.html
Copyright © 2011-2022 走看看