Design Circular Queue LeetCode solution in JavaScript

1
class MyCircularQueue {
2

3
int head = -1;
4
int tail = -1;
5
int[] q;
6
int k;
7

8
public MyCircularQueue(int k) {
9
q = new int[k];
10
this.k = k;
11
}
12

13
public boolean enQueue(int value) {
14
if(head == -1 && tail == -1) {
15
// enqueue when the queue is empty
16
head = tail = 0;
17
q[tail] = value; // enQueue done
18
return true;
19
}
20
if((tail == k-1 && head == 0) || tail+1 == head) {
21
// queue is full
22
return false;
23
}
24
tail++;
25
if(tail == k) // condition for circularity
26
tail = 0;
27
q[tail] = value; // enQueue done
28
return true;
29
}
30

31
public boolean deQueue() {
32
if(head == -1) {
33
// check if q is already empty
34
return false;
35
}
36
if(head == tail) {
37
// only 1 element is there and head,tail both points same index
38
head = tail = -1; // deQueue done
39
return true;
40
}
41
head++; // deQueue done
42
if(head == k) // condition for circularity
43
head = 0;
44
return true;
45
}
46

47
public int Front() {
48
if(head == -1)
49
return -1;
50
return q[head];
51
}
52

53
public int Rear() {
54
if(tail == -1)
55
return -1;
56
return q[tail];
57
}
58

59
public boolean isEmpty() {
60
if(head == -1 && tail == -1)
61
return true;
62
return false;
63
}
64

65
public boolean isFull() {
66
if(tail == k-1 || tail+1 == head)
67
return true;
68
return false;
69
}
70
}
71

72
/**
73
* Your MyCircularQueue object will be instantiated and called as such:
74
* MyCircularQueue obj = new MyCircularQueue(k);
75
* boolean param_1 = obj.enQueue(value);
76
* boolean param_2 = obj.deQueue();
77
* int param_3 = obj.Front();
78
* int param_4 = obj.Rear();
79
* boolean param_5 = obj.isEmpty();
80
* boolean param_6 = obj.isFull();
81
*/

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0