题解:
在我的文章数据结构之——队列与循环队列 中,有关于循环队列的设计,包括本题没有考虑过的resize操作。
对于本题而言,我们利用数组data作为循环队列的底层实现,并且维护了两个指针front和tail分别指向队列的头元素和尾部元素。除此之外我们刻意浪费了一个位置:
这样做的原因是为了避免队列为空,和队列为满的判别条件发生冲突,也就是说,队列为空的判别条件为:
front == tail
而队列为满的条件是:
front == (tail+1)%data.length
搞清楚思路后,就可以写代码了,代码如下:
class MyCircularQueue {
private int[] data;
private int front;
private int tail;
/** Initialize your data structure here. Set the size of the queue to be k. */
public MyCircularQueue(int k) {
data = new int[k + 1];
front = 0;
tail = 0;
}
private int getSize(){
if(tail < front){
return data.length - front + tail;
}else{
return tail - front;
}
}
/** Insert an element into the circular queue. Return true if the operation is successful. */
public boolean enQueue(int value) {
if(getSize() == data.length - 1){
return false;
}else{
data[tail] = value;
tail = (tail + 1)%data.length;
return true;
}
}
/** Delete an element from the circular queue. Return true if the operation is successful. */
public boolean deQueue() {
if(getSize() == 0){
return false;
}else{
front = (front + 1) % data.length;
return true;
}
}
/** Get the front item from the queue. */
public int Front() {
if(isEmpty()){
return -1;
}
return data[front];
}
/** Get the last item from the queue. */
public int Rear() {
if(isEmpty()){
return -1;
}
return data[(front + getSize() - 1) % data.length];
}
/** Checks whether the circular queue is empty or not. */
public boolean isEmpty() {
return front == tail;
}
/** Checks whether the circular queue is full or not. */
public boolean isFull() {
return getSize() == data.length - 1;
}
}
/**
* 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();
*/
执行结果: