两栈实现队列和两队列实现栈(js)

一、两栈实现队列

var MyQueue = function() {
    this.stack1 = [] // 出栈使用
    this.stack2 = [] // 入栈使用
};

/** 
 * @param {number} value
 * @return {void}
 */
MyQueue.prototype.in = function(value) {
    while(this.stack1.length) {
        this.stack2.push(this.stack1.pop())
    }
    this.stack2.push(value)
};

/**
 * @return {number}
 */
MyQueue.prototype.out = function() {
    while(this.stack2.length) {
        this.stack1.push(this.stack2.pop())
    }
    return this.stack1.pop() || -1
};

二、两队列实现栈

代码:

var MyStack = function() {
    this.queue1 = [] // 主队列
    this.queue2 = [] // 辅助队列
};

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

/**
 * @return {number}
 */
MyStack.prototype.pop = function() {
    while (this.queue1.length > 1) {
        this.queue2.push(this.queue1.shift())
    }
    const out = this.queue1.shift()
    while (this.queue2.length) {
        // 把元素放回主队列,确保每次不管是入栈还是出栈操作前所有元素都在主队列
        this.queue1.push(this.queue2.shift())
    }
    return out
};

猜你喜欢

转载自blog.csdn.net/qq_43119912/article/details/125784056