day10打卡

第五部分 栈与队列

1. 理论基础

栈是先进后出,队列是先进先出
js数组的push和pop是尾进尾出,push和shift是尾进头出

2. 用栈实现队列

用两个栈实现队列(只能用push和pop)。


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

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

/**
 * @return {number}
 */
MyQueue.prototype.pop = function() {
    if(!this.outStack.length) {
        this.in2out();
    }
    return this.outStack.pop();
};

/**
 * @return {number}
 */
MyQueue.prototype.peek = function() {
    if (!this.outStack.length) {
        this.in2out();
    }
    return this.outStack[this.outStack.length - 1];
};

/**
 * @return {boolean}
 */
MyQueue.prototype.empty = function() {
    return this.outStack.length === 0 && this.inStack.length === 0;
};

MyQueue.prototype.in2out = function() {
    while(this.inStack.length) {
        this.outStack.push(this.instack.pop());
    }
}

3. 用队列实现栈

用一个队列实现栈,只要在入栈时将队列里原来的元素全出队再入队就可以。

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

/** 
 * @param {number} x
 * @return {void}
 */
MyStack.prototype.push = function(x) {
    let size = this.queue.length;
    this.queue.push(x);
    for(let i = 0; i < size; i++) {
        this.queue.push(this.queue.shift());
    }
};

/**
 * @return {number}
 */
MyStack.prototype.pop = function() {
    return this.queue.shift();
};

/**
 * @return {number}
 */
MyStack.prototype.top = function() {
    return this.queue[0];
};

/**
 * @return {boolean}
 */
MyStack.prototype.empty = function() {
    return !this.queue.length;
};

你可能感兴趣的:(算法打卡,算法)