• 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();
        }
    }
    
  • 相关阅读:
    排序算法:冒泡和快排 摘自网络
    C语言内存讲解
    查找算法:折半查找
    SQL 相关知识
    位运算 C++
    设计模式学习3 观察者模式
    实验四——多分支结构及本章总结
    作业3for语句及分支结构elseif
    作业心得
    第二次作业及总结数据类型和运算符
  • 原文地址:https://www.cnblogs.com/CodeSPA/p/13566881.html
Copyright © 2020-2023  润新知