码迷,mamicode.com
首页 > 其他好文 > 详细

225. Implement Stack using Queues

时间:2020-06-24 12:04:42      阅读:54      评论:0      收藏:0      [点我收藏+]

标签:returns   var   cti   func   OLE   boolean   function   structure   anti   

/**
 * 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()
 */

 

225. Implement Stack using Queues

标签:returns   var   cti   func   OLE   boolean   function   structure   anti   

原文地址:https://www.cnblogs.com/strivegys/p/13186662.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!