数据结构与算法之双端队列

  • 指的是允许同时从队尾与对首两端进行存取操作的队列,操作更加灵活。
  • 与js中的数组操作十分相似,只是不允许在数组两端以外的位置进行存取操作。

我们要实现的功能:

  • addFront/addBack:添加功能
  • removeFront/removeBack:删除功能
  • frontTop/backTop:获取对首和队尾的值

基于对象实现

  • 队首添加,只需要更新 head 索引值,递减
  • 队首移除,只需要更新 head 索引值,递增
  • 队尾添加,正常更新 count 即可,递增
  • 队尾移除,正常更新 count 即可,递减
class Deque {
  constructor () {
    this.queue = {}
    this.count = 0
    this.head = 0
  }

  // 对首添加
  addFront (item) {
    this.queue[--this.head] = item
  }

  // 队尾添加
  addBack (item) {
    // 注意这里是后加,因为需要先从0的位置添加
    // 因为队首添加时,从-1开始了
    this.queue[this.count++] = item
  }

  // 对首移除
  removeFront () {
    if (this.isEmpty()) {
      return
    }

    const headData = this.queue[this.head]
    delete this.queue[this.head++]
    return headData
  }

  // 队尾删除
  removeBack () {
    if (this.isEmpty()) {
      return
    }

    const backData = this.queue[this.count - 1]
    delete this.queue[--this.count]
    return backData
  }

  // 获取对首值
  frontTop () {
    if (this.isEmpty()) {
      return
    }
    return this.queue[this.head]
  }

  // 获取对尾值
  backTop () {
    if (this.isEmpty()) {
      return
    }
    return this.queue[this.count - 1]
  }

  isEmpty () {
    return this.size() === 0
  }

  size () {
    return this.count - this.head
  }
}

const deq = new Deque()

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值