• 程序员面试金典-面试题 03.04. 化栈为队


    题目:

    实现一个MyQueue类,该类用两个栈来实现一个队列。


    示例:

    MyQueue queue = new MyQueue();

    queue.push(1);
    queue.push(2);
    queue.peek(); // 返回 1
    queue.pop(); // 返回 1
    queue.empty(); // 返回 false

    说明:

    你只能使用标准的栈操作 -- 也就是只有 push to top, peek/pop from top, size 和 is empty 操作是合法的。
    你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
    假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)。

    分析:

    利用双栈实现一个队列,因为栈的出栈顺序和队列的出栈顺序正好相反,那么我们可以再用一个栈,当需要弹出队列时,将栈内的元素依次弹出加入到新的栈中,此时新栈的出栈顺序就和队列要求的出栈顺序相同了。注意只有在出队栈为空时,才进行转入操作。

    程序:

    class MyQueue {
    
        /** Initialize your data structure here. */
        public MyQueue() {
            pushStack = new Stack<Integer>();
            popStack = new Stack<Integer>();
        }
        
        /** Push element x to the back of queue. */
        public void push(int x) {
            pushStack.push(x);
        }
        
        /** Removes the element from in front of queue and returns that element. */
        public int pop() {
            if(popStack.isEmpty()){
                while(!pushStack.isEmpty()){
                    popStack.push(pushStack.pop());
                }
            }
            return popStack.pop();
        }
        
        /** Get the front element. */
        public int peek() {
            if(popStack.isEmpty()){
                while(!pushStack.isEmpty()){
                    popStack.push(pushStack.pop());
                }
            }
            return popStack.peek();
        }
        
        /** Returns whether the queue is empty. */
        public boolean empty() {
            return pushStack.isEmpty() && popStack.isEmpty();
        }
    
        private Stack<Integer> pushStack;
        private Stack<Integer> popStack;
    }
    
    /**
     * 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();
     */
  • 相关阅读:
    Mysql数据操作指令
    Mysql列属性
    Mysql表的对应关系
    Mysql中的一些类型
    Mysql笔记
    (三) rest_framework 权限与限流源码梳理
    (二) rest_framework 认证源码流程与配置
    (一) rest_framework 视图入口
    django_celery_beat
    GRPC
  • 原文地址:https://www.cnblogs.com/silentteller/p/12420736.html
Copyright © 2020-2023  润新知