通过万岁!!!
java代码
class MyCircularQueue {
int[] queue;
int l = 0, r = 0;
boolean isFull;
int size;
public MyCircularQueue(int k) {
queue = new int[k];
isFull = false;
size = k;
}
public boolean enQueue(int value) {
if (isFull) {
return false;
}
if ((r + 1) % size == l) {// 加完了,满了
queue[(r++) % size] = value;
r %= size;
isFull = true;
return true;
} else {
queue[(r++) % size] = value;
r %= size;
return true;
}
}
public boolean deQueue() {
if (l == r && !isFull) {// 不满,并且两个指针相遇
return false;
} else {
l++;
l = l % size;
isFull = false;
return true;
}
}
public int Front() {
if (l == r && !isFull) {
return -1;
} else {
return queue[l];
}
}
public int Rear() {
if (l == r && !isFull) {
return -1;
} else {
return queue[r - 1 < 0 ? r - 1 + size : r - 1];
}
}
public boolean isEmpty() {
return l == r && !isFull;
}
public boolean isFull() {
return isFull;
}
}