一、题目要求
二、题目分析
循环队列为了克服假溢出的现象,当尾部添加元素的同时,头部删除元素,当添加的元素到达了最末端,此时造成了“队列已满”的现象,但实际上因为头部的删除,还留有大量空间。
为了解决这一问题,可以采用循环队列。
也就是用rear指向尾部,front指向头部。把队列从逻辑上看成一个环,如下图所示:
三、代码
class MyCircularQueue {
private int front;;
private int rear;
private int[] elem;
/** Initialize your data structure here. Set the size of the queue to be k. */
public MyCircularQueue(int k) {
this.elem=new int[k+1];
this.front=0;
this.rear=0;
}
/** Insert an element into the circular queue. Return true if the operation is successful. */
public boolean enQueue(int value) {
if(isFull()){
return false;
}
this.elem[this.rear]=value;
this.rear=(this.rear+1)%this.elem.length;
return true;
}
/** Delete an element from the circular queue. Return true if the operation is successful. */
public boolean deQueue() {
if(isEmpty()){
return false;
}
this.front=(this.front+1)%this.elem.length;
return true;
}
/** Get the front item from the queue. */
public int Front() {
if(isEmpty()){
return -1;
}else{
return this.elem[this.front];
}
}
/** Get the last item from the queue. */
public int Rear() {
if(isEmpty()){
return -1;
}else{
int index=(this.rear==0)?this.elem.length-1:this.rear-1;
return this.elem[index];
}
}
/** Checks whether the circular queue is empty or not. */
public boolean isEmpty() {
if(this.front==this.rear){
return true;
}
return false;
}
/** Checks whether the circular queue is full or not. */
public boolean isFull() {
if((this.rear+1)%this.elem.length==this.front){
return true;
}
return false;
}
}