题目来源:https://leetcode.com/explore/learn/card/queue-stack/228/first-in-first-out-data-structure/1337/
class MyCircularQueue {
int[] circularQueue = null;
int headPos, rearPos = -1, amount;
/** Initialize your data structure here. Set the size of the queue to be k. */
public MyCircularQueue(int k) {
circularQueue = new int[k];
}
/** Insert an element into the circular queue. Return true if the operation is successful. */
public boolean enQueue(int value) {
if (isFull()) return false;
if (rearPos < circularQueue.length-1) rearPos++;
else rearPos = (rearPos+1) % circularQueue.length;
circularQueue[rearPos] = value;
amount++;
return true;
}
/** Delete an element from the circular queue. Return true if the operation is successful. */
public boolean deQueue() {
if (isEmpty()) return false;
headPos = ++headPos % circularQueue.length;
amount--;
return true;
}
/** Get the front item from the queue. */
public int Front() {
if (isEmpty()) return -1;
return circularQueue[headPos];
}
/** Get the last item from the queue. */
public int Rear() {
if (isEmpty()) return -1;
return circularQueue[rearPos];
}
/** Checks whether the circular queue is empty or not. */
public boolean isEmpty() {
return amount == 0;
}
/** Checks whether the circular queue is full or not. */
public boolean isFull() {
return amount == circularQueue.length;
}
}
/**
* Your MyCircularQueue object will be instantiated and called as such:
* MyCircularQueue obj = new MyCircularQueue(k);
* boolean param_1 = obj.enQueue(value);
* boolean param_2 = obj.deQueue();
* int param_3 = obj.Front();
* int param_4 = obj.Rear();
* boolean param_5 = obj.isEmpty();
* boolean param_6 = obj.isFull();
*/