代码随想录算法训练营day10 | 理论基础 、 232.用栈实现队列 225. 用队列实现栈


学习时间:

晚上七点-晚上八点


理论基础

文章链接


232.用栈实现队列

题目链接/文章讲解/视频讲解

思路:

使用栈来模式队列的行为,如果仅仅用一个栈,是一定不行的,所以需要两个栈一个输入栈,一个输出栈,这里要注意输入栈和输出栈的关系。

代码实现:

class MyQueue {
      constructor() {
        this.stackIn = [];
        this.stackOut = [];
      }
      push (x) {
        this.stackIn.push(x)
      }
      pop () {
        const stackOutLen = this.stackOut.length
        //如果输出栈里有元素 直接弹出
        if (stackOutLen) {
          return this.stackOut.pop()
        }
        //如果没有元素 并且输入栈长度不为空 就从输入栈里拿元素放到输出栈里 在弹出
        while (this.stackIn.length) {
          this.stackOut.push(this.stackIn.pop())
        }
        return this.stackOut.pop()

      }
      peek () {
        //将x先提出来 然后再放回去
        const x = this.pop()
        this.stackOut.push(x)
        return x
      }
      empty () {
        return !this.stackIn.length && !this.stackOut.length
      }

    }

225. 用队列实现栈

题目链接/文章讲解/视频讲解

思路:

队列是先进先出的规则,把一个队列中的数据导入另一个队列中,数据的顺序并没有变,并没有变成先进后出的顺序。

所以用栈实现队列, 和用队列实现栈的思路还是不一样的,这取决于这两个数据结构的性质。

但是依然还是要用两个队列来模拟栈,只不过没有输入和输出的关系,而是另一个队列完全用来备份的!

代码实现:

 class MyStack {
      constructor() {
        this.queue1 = [];
        this.queue2 = [];
      }
      push (x) {
        this.queue1.push(x)
      }
      pop () {
        if (!this.queue1.length) {
          [this.queue1, this.queue2] = [this.queue2, this.queue1]
        }
        while (this.queue1.length > 1) {
          this.queue2.push(this.queue1.shift())
        }
        return this.queue1.shift()
      }
      top () {
        const x = this.pop()
        this.queue1.push(x)
        return x
      }
      empty () {
        return !this.queue1.length && !this.queue2.length
      }
    }
    //使用一个队列实现
    class MyStackOne {
      constructor() {
        this.queue = []
      }
      push (x) {
        this.queue.push(x)
      }
      pop () {
        let size = this.queue.length
        while (size-- > 1) {
          //不停地取出队列的第一个元素 然后再插到最后去
          this.queue.push(this.queue.shift())
        }
        return this.queue.shift()
      }
      top () {
        const x = this.pop()
        this.queue.push(x)
        return x
      }
      empty () {
        return !this.queue.length
      }
    }

总结:

初见队列和栈 总体来说较容易理解 继续加油!!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值