From 5d990d9e6ed0d76f322f0caaac77f2bc566e409a Mon Sep 17 00:00:00 2001 From: Manish Date: Tue, 22 Aug 2023 10:58:41 +1000 Subject: [PATCH] Data Structures: Create a Circular Queue --- Data Structures/circularQueue.js | 42 ++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Data Structures/circularQueue.js diff --git a/Data Structures/circularQueue.js b/Data Structures/circularQueue.js new file mode 100644 index 0000000..cad579c --- /dev/null +++ b/Data Structures/circularQueue.js @@ -0,0 +1,42 @@ +class CircularQueue { + constructor(size) { + this.queue = []; + this.read = 0; + this.write = 0; + this.max = size - 1; + + while (size > 0) { + this.queue.push(null); + size--; + } + } + + print() { + return this.queue; + } + + enqueue(item) { + // Only change code below this line + if (this.queue[this.write] === null) { + this.queue[this.write++] = item; + if (this.write > this.max) this.write = 0; + return item; + } + return null; + // Only change code above this line + } + + dequeue() { + // Only change code below this line + if (this.queue[this.read] === null) { + return null; + } + const item = this.queue[this.read]; + this.queue[this.read++] = null; + if (this.read > this.max) this.read = 0; + return item; + // Only change code above this line + } +} + +const q = new CircularQueue(5);