实现效果
代码如下:
class MyCircularQueue {
private int[] content;
private int head;
private int tail;
private int length;
/** Initialize your data structure here. Set the size of the queue to be k. */
public MyCircularQueue(int k) {
length = k+1;
content = new int[k+1];
head = 0;
tail = 0;
}
/** Insert an element into the circular queue. Return true if the operation is successful. */
public boolean enQueue(int value) {
if((tail+1)%length==head){
return false;
}
content[tail] = value;
tail = (tail+1)%length;
return true;
}
/** Delete an element from the circular queue. Return true if the operation is successful. */
public boolean deQueue() {
if(tail==head){
return false;
}
head = (head+1)%length;
return true;
}
/** Get the front item from the queue. */
public int Front() {
if(isEmpty()){
return -1;
}
return content[head];
}
/** Get the last item from the queue. */
public int Rear() {
if(isEmpty()){
return -1;
}
return content[(tail-1+length)%length];
}
/** Checks whether the circular queue is empty or not. */
public boolean isEmpty() {
return head==tail;
}
/** Checks whether the circular queue is full or not. */
public boolean isFull() {
return (tail+1)%length==head;
}
}
/**
* 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();
*/
过程
很凑巧,我看极客时间的《数据结构与算法之美》的时候正好看了队列,并且正好顺手写了一个循环队列,就抽到了这道题。循环队列最重要的判满判空,满就是对看看对尾指针有没有追上头指针,空就是看看头指针有没有反向追上头指针(正方向是指沿着head或者tail变大的方向,到数组边界的时候取余进行循环,具体参考这篇)。另外Rear方法和Front方法可以写的更优雅一些:
/** Get the front item from the queue. */
public int Front() {
return isEmpty()?-1:content[head];
}
/** Get the last item from the queue. */
public int Rear() {
return isEmpty()?-1:content[(tail-1+length)%length];
}