Design Circular Queue LeetCode solution in Java

1
class MyCircularQueue {
2

3
private int front;
4
private int rear;
5
private int[] arr;
6
private int cap;
7

8
private int next(int i) { // to get next idx after i in circular queue
9
return (i + 1) % cap;
10
}
11

12
private int prev(int i) { // to get prev idx before i in circular queue
13
return (i + cap - 1) % cap;
14
}
15

16
// rest is as simple as implmenting a normal queue using array.
17
public MyCircularQueue(int k) {
18
arr = new int[k];
19
cap = k;
20
front = -1;
21
rear = -1;
22
}
23

24
public boolean enQueue(int value) {
25
if (isFull()) return false;
26
if (front == -1) {
27
front = 0;
28
rear = 0;
29
arr[rear] = value;
30
return true;
31
}
32
rear = next(rear);
33
arr[rear] = value;
34
return true;
35
}
36

37
public boolean deQueue() {
38
if (isEmpty()) return false;
39
if (front == rear) {
40
front = -1;
41
rear = -1;
42
return true;
43
}
44
front = next(front);
45
return true;
46
}
47

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

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

58
public boolean isEmpty() {
59
return front == -1;
60
}
61

62
public boolean isFull() {
63
return front != -1 && next(rear) == front;
64
}
65
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0