在 JavaScript 中实现循环队列环形缓冲区
循环队列
循环队列是一种线性数据结构,其操作基于 FIFO(先进先出)原则,最后一个位置连接回第一个位置形成一个环。它也被称为“环形缓冲区”。
循环队列的优点之一是可以利用队列前面的空间。在普通队列中,一旦队列已满,即使队列前面有空间,也不能插入下一个元素。但使用循环队列,我们可以使用该空间来存储新值。
问题
我们需要设计在 JavaScript 中实现循环队列,该队列可以支持以下操作:
MyCircularQueue(k) - 构造函数,将队列的大小设置为 k。
Front() - 获取队列中的第一个元素。如果队列为空,则返回 -1。
Rear() - 获取队列中的最后一个元素。如果队列为空,则返回 -1。
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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP