-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathqueue-circular.js
More file actions
60 lines (50 loc) · 1.24 KB
/
queue-circular.js
File metadata and controls
60 lines (50 loc) · 1.24 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
export default class CircularQueue {
constructor(capacity) {
this.capacity = capacity;
this.items = new Array(capacity);
this.currentLength = 0;
this.front = 0;
this.rear = -1;
}
isFull() {
return this.currentLength === this.capacity;
}
isEmpty() {
return this.currentLength === 0;
}
enqueue(element) {
if (this.isFull()) {
return console.log("Circular queue is full. Unable to enqueue element.");
}
this.rear = (this.rear + 1) % this.capacity;
this.items[this.rear] = element;
this.currentLength++;
}
dequeue() {
if (this.isEmpty()) {
return console.log("Circular queue is empty. Unable to dequeue element.");
}
const element = this.items[this.front];
this.items[this.front] = undefined;
this.front = (this.front + 1) % this.capacity;
this.currentLength--;
return element;
}
peek() {
if (this.isEmpty()) {
return console.log("Queue is empty");
}
return this.items[this.front];
}
print() {
let result = [];
let count = 0;
let index = this.front;
while (count < this.currentLength) {
result.push(this.items[index]);
index = (index + 1) % this.capacity;
count++;
}
return result;
}
}