第五章 栈与队列part01

算法

1. 232 Implement Queue using Stacks

function MyQueue() {
    this.stack1 = [];
    //入队操作, stack1尾部为队列的尾部

    this.stack2 = [];
    //出队操作,使用一个数组来翻转元素的顺序
}

MyQueue.prototype.push = function (x) {
    this.stack1.push(x);
}

MyQueue.prototype.pop = function () {
    //如果stack2中没有元素,那么将stack1中元素翻转顺序填入stack2
    if (this.stack2.length === 0) {
        while (this.stack1.length !== 0) {
            this.stack2.push(this.stack1.pop())
        }
    }

    //数组的pop函数是删除并返回数组最后一位
    return this.stack2.pop();

}

MyQueue.prototype.peek = function () {
    //如果stack2中没有元素,那么将stack1中元素翻转顺序填入stack2
    if (this.stack2.length === 0) {
        while (this.stack1.length !== 0) {
            this.stack2.push(this.stack1.pop())
        }
    }

    return this.stack2[this.stack2.length - 1]
}

MyQueue.prototype.empty = function () {
    return this.stack1.length === 0 && this.stack2.length === 0;
}



2. 225 Implement Stack using Queues

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

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());
    }

}

MyStack.prototype.pop = function () {
    return this.queue.shift();
}

MyStack.prototype.peek = function () {
    return this.queue[0];
}

MyStack.prototype.empty = function () {
    //检查栈是否为空
    return this.queue.length === 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值