# 循环队列
public class CircularQueue {
int[] data;
// 真实能够存储的元素数量为 cap-1,留出一位判断空还是满
int cap;
int size;
// head 指向当前第一个元素
int head = 0;
// tail 指向下一个可以插入的空位置
int tail = 0;
private boolean isFull() {
return (tail + 1) % cap == head;
}
private boolean isEmpty() {
return head == tail;
}
public int size() {
return size;
}
public CircularQueue(int cap) {
this.cap = cap + 1;
data = new int[this.cap];
}
public void offer(int val) {
if (isFull()) return;
size++;
data[tail] = val;
tail = (tail + 1) % cap;
}
public int poll() {
if (isEmpty()) return -1;
size--;
int toPop = data[head];
head = (head + 1) % cap;
return toPop;
}
}
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
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
← LFU