-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCircularQueue.js
More file actions
71 lines (61 loc) · 1.55 KB
/
Copy pathCircularQueue.js
File metadata and controls
71 lines (61 loc) · 1.55 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
class CircularQueue {
// FIFO
constructor(size) {
this.queue = [];
this.maxSize = size;
this.head = -1; // position to dequeu from
this.tail = -1; // position to enqueu on
}
Front() {
if (this.isEmpty()) {
return -1; // element not found
}
return this.queue[this.head];
}
Rear() {
if (this.isEmpty()) {
return -1;
}
return this.queue[this.tail]
}
enQueue(value) {
if (this.isFull()) {
return false;
}
if (this.isEmpty()) {
this.head = 0;
}
this.tail = (this.tail + 1) % this.maxSize;
this.queue[this.tail] = value;
return true;
}
deQueue() {
if (this.isEmpty()) {
return false;
}
delete this.queue[this.head];
if (this.head === this.tail) {
this.head = -1;
this.tail = -1;
return true;
}
this.head = (this.head + 1) % this.maxSize;
return true;
}
isEmpty() {
return this.head === -1;
}
isFull() {
return ((this.tail + 1) % this.maxSize) == this.head;
}
}
const myCircularQueue = new CircularQueue(3);
console.log(myCircularQueue.enQueue(1)); // return True
console.log(myCircularQueue.enQueue(2)); // return True
console.log(myCircularQueue.enQueue(3)); // return True
console.log(myCircularQueue.enQueue(4)); // return False
console.log(myCircularQueue.Rear()); // return 3
console.log(myCircularQueue.isFull()); // return True
console.log(myCircularQueue.deQueue()); // return True
console.log(myCircularQueue.enQueue(4)); // return True
console.log(myCircularQueue.Rear()); // return 4