zoukankan      html  css  js  c++  java
  • 225. Implement Stack using Queues

    /**
     * Initialize your data structure here.
     */
    var MyStack = function() {
        this.inQueue = [];
        this.outQueue = [];
    };
    
    /**
     * Push element x onto stack. 
     * @param {number} x
     * @return {void}
     */
    MyStack.prototype.push = function(x) {
        this.inQueue.push(x);
    };
    
    /**
     * Removes the element on top of the stack and returns that element.
     * @return {number}
     */
    MyStack.prototype.pop = function() {
        this.checkQueue();
        return this.outQueue.shift();
    };
    
    /**
     * Get the top element.
     * @return {number}
     */
    MyStack.prototype.top = function() {
        this.checkQueue();
        return this.outQueue[0];
    };
    /**
    * check the queue element
    * @return { void }
    */
    MyStack.prototype.checkQueue = function() {
        while(this.outQueue.length) {
            this.inQueue.unshift(this.outQueue.shift());
        }
        
        while(this.inQueue.length) {
            this.outQueue.push(this.inQueue.pop());
        }
    }
    /**
     * Returns whether the stack is empty.
     * @return {boolean}
     */
    MyStack.prototype.empty = function() {
        return (this.inQueue.length == 0 && this.outQueue.length == 0);
    };
    
    /** 
     * Your MyStack object will be instantiated and called as such:
     * var obj = new MyStack()
     * obj.push(x)
     * var param_2 = obj.pop()
     * var param_3 = obj.top()
     * var param_4 = obj.empty()
     */
  • 相关阅读:
    正则表达式分类
    数据思维二三事
    关于编程语言的一些趣史
    重构后端模板文件的一种实践
    为什么程序员需要知道互联网行业发展史
    探秘JS的异步单线程
    Nerd的畅销产品
    Nerd的套现ATM机
    网络传输与加密 (2)
    网络传输与加密
  • 原文地址:https://www.cnblogs.com/strivegys/p/13186662.html
Copyright © 2011-2022 走看看