MCPcopy Create free account
hub / github.com/TheAlgorithms/JavaScript / CircularQueue

Class CircularQueue

Data-Structures/Queue/CircularQueue.js:6–87  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

4// Doesn’t use dynamic memory so No memory leaks
5
6class CircularQueue {
7 constructor(maxLength) {
8 this.queue = []
9 this.front = 0
10 this.rear = 0
11 this.maxLength = maxLength
12 }
13
14 // ADD ELEMENTS TO QUEUE
15 enqueue(value) {
16 if (this.checkOverflow()) return
17 if (this.checkEmpty()) {
18 this.front += 1
19 this.rear += 1
20 } else {
21 if (this.rear === this.maxLength) {
22 this.rear = 1
23 } else this.rear += 1
24 }
25 this.queue[this.rear] = value
26 }
27
28 // REMOVES ELEMENTS
29 dequeue() {
30 if (this.checkEmpty()) {
31 // UNDERFLOW
32 return
33 }
34 const y = this.queue[this.front]
35 this.queue[this.front] = '*'
36 if (!this.checkSingleelement()) {
37 if (this.front === this.maxLength) this.front = 1
38 else {
39 this.front += 1
40 }
41 }
42
43 return y // Returns the removed element and replaces it with a star
44 }
45
46 // checks if the queue is empty or not
47 checkEmpty() {
48 if (this.front === 0 && this.rear === 0) {
49 return true
50 }
51 }
52
53 checkSingleelement() {
54 if (this.front === this.rear && this.rear !== 0) {
55 this.front = this.rear = 0
56 return true
57 }
58 }
59
60 // Checks if max capacity of queue has been reached or not
61 checkOverflow() {
62 if (
63 (this.front === 1 && this.rear === this.maxLength) ||

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected