2020-08-26 用两个栈实现队列

2020-08-26  本文已影响0人  再见地平线_e930

1.栈:先进后出,后进先出,可以用数组的 push 和 pop 方法模拟入栈和出栈

2.队列:先进先出,后进后出。

题目要求用两个栈模拟队列,我们用push方法往 stack1 中加入元素可以看作入队列,再从 stack1 中通过 pop方法拿出元素,再 push 进 stack2 中,这样 stack2 中元素的顺序就刚好和 stack1 中元素的顺序相反了,再通过 pop方法从 stack2 中取出元素就可以看作为出队列

var CQueue = function() {
    this.stack1 = []; // 1 2 3   4
    this.stack2 = []; // 3 2 1 => pop 4 -> 3 -> 2 -> 1
};

/** 
 * @param {number} value
 * @return {void}
 */
CQueue.prototype.appendTail = function(value) {
    this.stack1.push(value);
};

/**
 * @return {number}
 */
CQueue.prototype.deleteHead = function() {
    if(!this.stack1.length && !this.stack2.length) {
            return -1;
        }
    
    if(this.stack2.length) {
        return this.stack2.pop()
    } else {
        while(this.stack1.length) {
            this.stack2.push(this.stack1.pop())
        }
        // const length = this.stack1.length
        // for(let i=0; i<length; i++) {
        //     this.stack2.push(this.stack1.pop())
        // }
        return this.stack2.pop()
    }
};

/**
 * Your CQueue object will be instantiated and called as such:
 * var obj = new CQueue()
 * obj.appendTail(value)
 * var param_2 = obj.deleteHead()
 */
上一篇 下一篇

猜你喜欢

热点阅读