一定要注意,循环队列中,有一个元素的空间是浪费的,所以,在创建队列时,数组的大小,要比题目给定的长度大一个单位,也就是说为 size+1 才能够满足本题的要求
public class MyCircularQueue {
int[] myQueue; //队列
int head; //队首
int tail; //队尾
int length; //队列长度
/*队列初始化*/
public MyCircularQueue(int k) {
length = k+1;
myQueue = new int[length];
head = 0;
tail = length-1;
}
/*入队*/
public boolean enQueue(int value) {
if(isFull()) return false;//队列满时
tail = (tail+1)%length;
myQueue[tail] = value;
return true;
}
/*出队*/
public boolean deQueue() {
if(!isEmpty()) //队列非空时
{
head = (head+1)%length;
return true;
}
return false; //队列为空时
}
/*获取队首元素*/
public int Front() {
if(isEmpty()) return -1;
return myQueue[head];
}
/*获取队尾元素*/
public int Rear() {
if(isEmpty()) return -1;
return myQueue[tail];
}
/*队列是否为空*/
public boolean isEmpty() {
return (tail+1) % length == head;
}
/*队列是否为满*/
public boolean isFull() {
return (tail+2) % length == head;
}
}