Javascriptのキュークラス
例
class Queue {
constructor(maxSize) {
// Set default max size if not provided
if (isNaN(maxSize)) {
maxSize = 10;
}
this.maxSize = maxSize;
// Init an array that'll contain the queue values.
this.container = [];
}
// Helper function to display all values while developing
display() {
console.log(this.container);
}
// Checks if queue is empty
isEmpty() {
return this.container.length === 0;
}
// checks if queue is full
isFull() {
return this.container.length >= this.maxSize;
}
enqueue(element) {
// Check if Queue is full
if (this.isFull()) {
console.log("Queue Overflow!"); return;
}
// Since we want to add elements to end, we'll just push them.
this.container.push(element);
}
dequeue() {
// Check if empty
if (this.isEmpty()) {
console.log("Queue Underflow!");
return;
}
return this.container.shift();
}
peek() {
if (this.isEmpty()) {
console.log("Queue Underflow!");
return;
}
return this.container[0];
}
clear() {
this.container = [];
}
} -
Javascriptのキューデータ構造
キューは抽象的なデータ構造であり、スタックにいくぶん似ています。スタックとは異なり、キューは両端で開いています。一方の端は常にデータの挿入(エンキュー)に使用され、もう一方の端はデータの削除(デキュー)に使用されます。キューは先入れ先出し方式に従います。つまり、最初に保存されたデータ項目が最初にアクセスされます。 キューの実際の例としては、車両が最初に進入し、最初に退出する単一車線の一方通行道路があります。 次の図は、キューがどのように機能するかを示しています-
-
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>