代码随想录的第九天

42 阅读1分钟

代码随想录的第九天

232. 用栈实现队列

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

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

/**
 * @return {number}
 */
MyQueue.prototype.pop = function() {
    if (!this.outQueue.length) {
        while (this.inQueue.length) {
            this.outQueue.push(this.inQueue.pop())
        }
    }
    return this.outQueue.pop()
};

/**
 * @return {number}
 */
MyQueue.prototype.peek = function() {
    if (!this.outQueue.length) {
        while (this.inQueue.length) {
            this.outQueue.push(this.inQueue.pop())
        }
    }
    return this.outQueue[this.outQueue.length - 1]
};

/**
 * @return {boolean}
 */
MyQueue.prototype.empty = function() {
    return this.inQueue.length === 0 && this.outQueue.length === 0 ? true : false
};

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

思路:

1、用两个栈来实现队列,因为栈只能从入口处进行操作

2、然后入栈和队列操作一样

3、队列移除开头元素,因为栈只能从最后操作,所以需要先将栈进行倒下顺序然后操作

4、返回开头元素也是一个意思

225. 用队列实现栈

var MyStack = function() {
    this.inStack = []
    this.outStack = []
};

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

/**
 * @return {number}
 */
MyStack.prototype.pop = function() {
    if (!this.outStack.length) {
        while (this.inStack.length) {
            this.outStack.push(this.inStack.pop())
        }
    }
    const ans = this.outStack.shift()
    if (!this.inStack.length) {
        while (this.outStack.length) {
            this.inStack.push(this.outStack.pop())
        }
    }
    return ans
};

/**
 * @return {number}
 */
MyStack.prototype.top = function() {
    if (!this.outStack.length) {
        while (this.inStack.length) {
            this.outStack.push(this.inStack.shift())
        }
    }
    const out = this.outStack[this.outStack.length - 1]
    if (!this.inStack.length) {
        while (this.outStack.length) {
            this.inStack.push(this.outStack.shift())
        }
    }
    return out
};

/**
 * @return {boolean}
 */
MyStack.prototype.empty = function() {
    return this.outStack.length === 0 && this.inStack.length === 0? true : false
};

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

思路:

1、两个队列实现一个栈,需要注意的地方就是在inStack每次进行删除后,数组进行了改变,得到值之后需要进行还原然后在接着下一步操作,相当于以inStack为中心队列进行操作