JavaScriptでの循環キューリングバッファの実装
循環キュー
循環キューは、FIFO(先入れ先出し)の原理に基づいて操作が実行され、最後の位置が最初の位置に接続されて円を描く線形データ構造です。 「リングバッファ」とも呼ばれます。
循環キューの利点の1つは、キューの前のスペースを利用できることです。通常のキューでは、キューがいっぱいになると、キューの前にスペースがあっても次の要素を挿入できません。ただし、循環キューを使用すると、スペースを使用して新しい値を格納できます。
問題
次の操作をサポートできる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
-
JavaScriptでのキューの実装
以下は、JavaScriptでキューを実装するためのコードです。 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style>
-
JavaScriptでの線形検索の実装
以下は、JavaScriptで線形検索を実装するためのコードです- 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style>