-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcircular-queue.js
More file actions
61 lines (54 loc) · 1.38 KB
/
circular-queue.js
File metadata and controls
61 lines (54 loc) · 1.38 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
class CircularQueue {
constructor(size) {
this.items = [];
this.front = 0;
this.rear = -1;
this.size = size;
this.length = 0;
}
enqueue(item) {
if (this.length >= this.size) {
return "Queue limit exceeded";
}
else {
this.rear++;
this.items[this.rear % this.size] = item;
this.length++;
}
}
dequeue() {
if (this.isEmpty()) {
return "Queue is empty"
}
this.items[this.front % this.size] = null;
this.front++;
this.length--;
return true;
}
isEmpty() {
return this.items.length === 0;
}
peek() {
if (this.isEmpty()) {
return "Queue is empty"
}
return this.items[this.front % this.size];
}
print() {
return this.items.toString();
}
}
let queue = new CircularQueue(5);
console.log('Is queue Empty : ', queue.isEmpty());
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
queue.enqueue(4)
queue.enqueue(5)
console.log('Is queue Empty : ', queue.isEmpty());
console.log('Print the queue : ', queue.print())
console.log('Lookup for peek value : ', queue.peek())
console.log('Pop out top value : ', queue.dequeue())
console.log('Lookup for peek value : ', queue.peek())
queue.enqueue(6)
console.log('Print the queue : ', queue.print())