Design Circular Queue LeetCode solution in C++

1
class MyCircularQueue {
2
int head = -1;
3
int tail = -1;
4
int[] q;
5
int k;
6

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

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

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

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

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

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

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

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

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0