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

    /**
     * Initialize your data structure here.
     */
    var MyQueue = function() {
        this.stack1 = [];
        this.stack2 = [];
    };
    
    /**
     * Push element x to the back of queue. 
     * @param {number} x
     * @return {void}
     */
    MyQueue.prototype.push = function(x) {
        this.stack1.push(x);
    };
    
    /**
     * Removes the element from in front of queue and returns that element.
     * @return {number}
     */
    MyQueue.prototype.pop = function() {
        this.checkStack();
        return this.stack2.pop();
    };
    
    /**
     * Get the front element.
     * @return {number}
     */
    MyQueue.prototype.peek = function() {
         this.checkStack();
         return this.stack2[this.stack2.length - 1];
    };
    MyQueue.prototype.checkStack = function() {
        if(!this.stack2.length) {
            while(this.stack1.length) {
                this.stack2.push(this.stack1.pop());
            }
        }
    }
    /**
     * Returns whether the queue is empty.
     * @return {boolean}
     */
    MyQueue.prototype.empty = function() {
        return (this.stack2.length == 0 && this.stack1.length == 0);
    };
    
    /** 
     * Your MyQueue object will be instantiated and called as such:
     * var obj = new MyQueue()
     * obj.push(x)
     * var param_2 = obj.pop()
     * var param_3 = obj.peek()
     * var param_4 = obj.empty()
     */
  • 相关阅读:
    UGO小组冲刺第一天
    day04_07-三个函数的区别
    day06_08 字符串
    day06_07 字典操作02
    day06_06 字典操作01
    day06_05 字典
    day06_04 购物车讲解02
    day06_03 购物车讲解01
    day06_02 元组
    day06_01 上节回顾
  • 原文地址:https://www.cnblogs.com/strivegys/p/13186651.html
Copyright © 2011-2022 走看看