zoukankan      html  css  js  c++  java
  • 232. Implement Queue using Stacks

    Implement the following operations of a queue using stacks.

    • push(x) -- Push element x to the back of queue.
    • pop() -- Removes the element from in front of queue.
    • peek() -- Get the front element.
    • empty() -- Return whether the queue is empty.
    Notes:
    • You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, and is empty operations are valid.
    • Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
    • You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

    第一想法是,push的时候直接把元素放入栈底,栈顶的元素保持为第一次入栈的元素,出栈时相当于出队。这种做法,push的时间复杂度是O(n),pop是O(1)。另外还需要一个stack,用来在push时存暂时出栈的元素。
    机智的做法是!首先,如果一直在push,早已入栈的元素一直在两个栈之间push和pop,其次,stack把所有元素pop到另一个栈,实际上已经变成了一个queue
    时间复杂度amortized o(1) 最差情况O(n)
    什么是amortized o(1), 还有什么是amortized o(1)? 如ArrayList的add操作
    public class MyQueue {
        Stack<Integer> stack;
        Stack<Integer> queue;
        /** Initialize your data structure here. */
        public MyQueue() {
            stack = new Stack<Integer>();
            queue = new Stack<Integer>();
        }
        
        /** Push element x to the back of queue. */
        public void push(int x) {
            stack.push(x);
        }
        
        /** Removes the element from in front of queue and returns that element. */
        public int pop() {
            if (queue.empty()) {
                while (!stack.empty()) {
                    queue.push(stack.pop());
                }
            }
            return queue.pop();
        }
        
        /** Get the front element. */
        public int peek() {
            if (queue.empty()) {
                while (!stack.empty()) {
                    queue.push(stack.pop());
                }
            }
            return queue.peek();
        }
        
        /** Returns whether the queue is empty. */
        public boolean empty() {
            if (stack.empty() && queue.empty()) {
                return true;
            } else {
                return false;
            }
        }
    }
    
    /**
     * Your MyQueue object will be instantiated and called as such:
     * MyQueue obj = new MyQueue();
     * obj.push(x);
     * int param_2 = obj.pop();
     * int param_3 = obj.peek();
     * boolean param_4 = obj.empty();
     */
    
  • 相关阅读:
    (CS模式)大学计算机基础考试系统
    四叶草的祝福
    做人的小故事!
    前天晚上回到北京了
    人生活的三种状态
    松口气了!
    Mysql一些基础用法
    云计算随想
    对vector与deque插值与遍历的性能数据
    gdb命令的常用调试选项
  • 原文地址:https://www.cnblogs.com/yuchenkit/p/7173070.html
Copyright © 2011-2022 走看看