-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path35-Circular Queue Implementation (Array-based).js
More file actions
90 lines (71 loc) · 1.45 KB
/
35-Circular Queue Implementation (Array-based).js
File metadata and controls
90 lines (71 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
class CircularQueue {
constructor(size) {
this.queue = new Array(size);
this.size = size;
this.front = -1;
this.rear = -1;
}
isEmpty() {
return this.front === -1;
}
isFull() {
return (
this.front === this.rear + 1 ||
(this.rear === this.size - 1 && this.front === 0)
);
}
enqueue(element) {
if (this.isFull()) {
console.log("Queue Overflow");
return;
}
if (this.front === -1) {
this.front = 0;
}
this.rear = (this.rear + 1) % this.size;
this.queue[this.rear] = element;
console.log(`${element} inserted`);
}
dequeue() {
if (this.isEmpty()) {
console.log("Queue Underflow");
return;
}
let element = this.queue[this.front];
if (this.front === this.rear) {
this.front = this.rear = -1;
} else {
this.front = (this.front + 1) % this.size;
}
console.log(`${element} removed`);
}
display() {
if (this.isEmpty()) {
console.log(`Queue is Empty`);
return;
}
let i = this.front;
let result = "";
while (true) {
result += this.queue[i] + " ";
if (i === this.rear) {
break;
}
i = (i + 1) % this.size;
}
console.log(result);
}
}
const cq = new CircularQueue(5);
cq.enqueue(10);
cq.enqueue(20);
cq.enqueue(30);
cq.enqueue(40);
console.log(cq);
cq.display();
cq.dequeue();
cq.dequeue();
cq.enqueue(50);
cq.enqueue(60);
console.log(cq);
cq.display();