622. Design Circular Queue

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
class MyCircularQueue {

private final int[] array;
private int headIndex;
private int tailIndex; // 即将插入元素的索引
private int size;

public MyCircularQueue(int k) {
this.array = new int[k];
this.headIndex = this.tailIndex = 0;
this.size = 0;
}

public boolean enQueue(int value) {
if (isFull()) {
return false;
}

array[tailIndex] = value;
size++;
tailIndex = (tailIndex + 1) % array.length;
return true;
}

public boolean deQueue() {
if (isEmpty()) {
return false;
}

size--;
headIndex = (headIndex + 1) % array.length;
return true;
}

public int Front() {
if (isEmpty()) {
return -1;
}

return array[headIndex];
}

public int Rear() {
if (size == 0) {
return -1;
}

return array[(tailIndex - 1 + array.length) % array.length];
}

public boolean isEmpty() {
return size == 0;
}

public boolean isFull() {
return size == array.length;
}
}

References

622. Design Circular Queue