```
class MyCircularQueue {
private int[] data;
private int head;
private int tail;
private int size;
/** Initialize your data structure here. Set the size of the queue to be k. */
public MyCircularQueue(int k) {
data = new int[k];
head = -1;
tail = -1;
//size是隊列的容量,數組的大小,為data.length,數組從0到 k-1 , ( k-1)+1 % k ==0,索引從末尾變為index = 0。
//0到k-2坐標設為a, (a+1)%k = a+1
size = k;
}
public boolean enQueue(int value) {
//隊列滿不能入隊
if (isFull() == true) {
return false;
}
//隊列空,頭指針需要初始化為0
if (isEmpty() == true) {
head = 0;
}
//隊尾指針移動到下一個位置,插入的第一個元素位置為(-1+1)%size =0
tail = (tail + 1) % size;
data[tail] = value;
return true;
}
public boolean deQueue() {
//隊為空,出隊失敗
if (isEmpty() == true) {
return false;
}
//如果head == tail 時,表明隊列中還有一個元素,這時隊頭隊尾指針都指向這個元素。
//這時調用出隊方法,隊為空,head與tail都需要變為-1
if (head == tail) {
head = -1;
tail = -1;
return true;
}
//head指針向下移動一位,表示隊頭元素已經出隊
head = (head + 1) % size;
return true;
}
public int Front() {
if (isEmpty() == true) {
return -1;
}
//返回隊頭元素
return data[head];
}
public int Rear() {
//隊空時,head==tail== -1
if (isEmpty() == true) {
return -1;
}
//返回隊尾元素
return data[tail];
}
//隊空時,head == -1
public boolean isEmpty() {
return head == -1;
}
// (tail+1)%size +1 == head時,隊滿, 隊尾不能再插入元素
public boolean isFull() {
return ((tail + 1) % size) == head;
}
}
```