Skip to content

Files

Latest commit

 

History

History
60 lines (52 loc) · 1.43 KB

0225. Implement Stack using Queues.md

File metadata and controls

60 lines (52 loc) · 1.43 KB

Screen Shot 2023-03-02 at 5 42 31 PM

Screen Shot 2023-03-02 at 5 42 42 PM

var MyStack = function() {
    this.inQueue = [];
    this.outQueue = [];
};

/** 
 * @param {number} x
 * @return {void}
 */
MyStack.prototype.push = function(x) {
    this.inQueue.push(x);
};

/**
 * @return {number}
 */
MyStack.prototype.pop = function() {
    while(this.inQueue.length > 1) {
        this.outQueue.push(this.inQueue.shift());
    }
    let pivot = this.inQueue.shift();
    [this.outQueue, this.inQueue] = [this.inQueue, this.outQueue];
    return pivot;
};

/**
 * @return {number}
 */
MyStack.prototype.top = function() {
     while(this.inQueue.length > 1) {
        this.outQueue.push(this.inQueue.shift());
    }
    let pivot = this.inQueue[0];
    this.outQueue.push(this.inQueue.shift());
    [this.outQueue, this.inQueue] = [this.inQueue, this.outQueue];
    return pivot;
};

/**
 * @return {boolean}
 */
MyStack.prototype.empty = function() {
    return this.inQueue.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()
 */