Day10 用栈实现队列|用队列实现栈

1.用栈实现队列 leetcode232

队列的特性是(先入先出),而的特性是(先入后出

需要用两个栈来模拟队列的特性,一个栈为入队栈,一个栈为出对栈

入栈时,直接pop进去

出栈时,如果出栈的数据为空时,需要把入栈中的所有数据导入进去,在弹出(如果没有全部导进去 会破坏整体的顺序,顺序乱了,无法正确的弹出数据)。如果不为空,则直接从出栈弹出数据就可以了。

var MyQueue = function () {
    this.stackIn = [];
    this.stackOut = [];
};

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

/**
 * @return {number}
 */
MyQueue.prototype.pop = function () {
    if (this.stackOut.length != 0) {
        return this.stackOut.pop()
    }
// 如果入栈中有数据,就全部导入到出栈里,避免顺序出现问题
    while (this.stackIn.length) {
        this.stackOut.push(this.stackIn.pop())
    }
    return this.stackOut.pop()

};

/**
 * @return {number}
 */
MyQueue.prototype.peek = function () {
// 复用pop函数,peek只取值,不用弹出,所以再push进去
    const x = this.pop();
    this.stackOut.push(x);
    return x
};

/**
 * @return {boolean}
 */
MyQueue.prototype.empty = function () {
    return !this.stackIn.length && !this.stackOut.length
};

2.用队列实现栈 leetcode225

只需要一个队列就可模拟栈

一个队列在模拟栈弹出元素的时候只要将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部,此时再去弹出元素就是栈的顺序了

1-》2-》3      可以将前面两个弹出来然后push到队尾 3-》1=》2  然后拿到3, 队列只剩下2,1 在将1弹出push到队尾 拿到2,以此类推

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

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

/**
 * @return {number}
 */
MyStack.prototype.pop = function () {
    let size = this.queue.length
// 不断弹出队首的,放到队尾去
    while (size > 1) {
        size--;
        this.queue.push(this.queue.shift())
    }
    return this.queue.shift()
};

/**
 * @return {number}
 */
MyStack.prototype.top = function () {
    let x = this.pop();
    this.queue.push(x)
    return x
};

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值