首页 > web前端 > js教程 > 正文

在JavaScript中实现循环队列环形缓冲区

王林
发布: 2023-08-22 17:57:08
转载
1067人浏览过

在javascript中实现循环队列环形缓冲区

循环队列

循环队列是一种线性数据结构,它的操作是基于FIFO(先进先出)原则进行的,并且最后一个位置连接回第一个位置,形成一个循环。它也被称为“环形缓冲区”。

循环队列的一个好处是我们可以利用队列前面的空间。在普通队列中,一旦队列变满,即使队列前面有空间,我们也无法插入下一个元素。但是使用循环队列,我们可以使用空间来存储新的值。

问题

我们需要在JavaScript中设计循环队列的实现,支持以下操作:

  • MyCircularQueue(k) - 构造函数,将队列的大小设置为k。

    立即学习Java免费学习笔记(深入)”;

  • Front() - 从队列中获取前面的项。如果队列为空,则返回-1。

  • Rear() - 从队列中获取最后一项。如果队列为空,则返回-1。

    BetterYeah AI
    BetterYeah AI

    基于企业知识库构建、训练AI Agent的智能体应用开发平台,赋能客服、营销、销售场景 -BetterYeah

    BetterYeah AI 110
    查看详情 BetterYeah AI
  • enQueue(value) - 将元素插入循环队列。如果操作成功,则返回true。

  • deQueue() - 从循环队列中删除一个元素。如果操作成功,则返回true。

  • isEmpty() - 检查循环队列是否为空。

  • isFull() - 检查循环队列是否已满。

示例

以下是代码 -

演示

const CircularQueue = function(k) {
   this.size = k
   this.queue = []
   this.start1 = 0
   this.end1 = 0
   this.start2 = 0
   this.end2 = 0
}
CircularQueue.prototype.enQueue = function(value) {
   if(this.isFull()) {
      return false
   }
   if(this.end2 <= this.size - 1) {
      this.queue[this.end2++] = value
   } else {
      this.queue[this.end1++] = value
   }
   return true
}
CircularQueue.prototype.deQueue = function() {
   if(this.isEmpty()) {
      return false
   }
   if(this.queue[this.start2] !== undefined) {
      this.queue[this.start2++] = undefined
   } else {
      this.queue[this.start1++] = undefined
   }
   return true
}
CircularQueue.prototype.Front = function() {
   if(this.isEmpty()) {
      return -1
   }
   return this.queue[this.start2] === undefined ? this.queue[this.start1] :    this.queue[this.start2]
}
CircularQueue.prototype.Rear = function() {
   if(this.isEmpty()) {
      return -1
   }
   return this.queue[this.end1 - 1] === undefined ? this.queue[this.end2 - 1] :    this.queue[this.end1 - 1]
}
CircularQueue.prototype.isEmpty = function() {
   if(this.end2 - this.start2 + this.end1 - this.start1 <= 0) {
      return true
   }
   return false
}
CircularQueue.prototype.isFull = function() {
   if(this.end2 - this.start2 + this.end1 - this.start1 >= this.size) {
      return true
   }
   return false
}
const queue = new CircularQueue(2);
console.log(queue.enQueue(1));
console.log(queue.enQueue(2));
console.log(queue.enQueue(3));
console.log(queue.Rear());
console.log(queue.isFull());
console.log(queue.deQueue());
console.log(queue.enQueue(3));
console.log(queue.Rear());
登录后复制

输出

true
true
false
2
true
true
true
3
登录后复制

以上就是在JavaScript中实现循环队列环形缓冲区的详细内容,更多请关注php中文网其它相关文章!

java速学教程(入门到精通)
java速学教程(入门到精通)

java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:tutorialspoint网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号