循环队列:
  1. 需要预留一个空间,即rear指向的空间,否则无法判断队列为空或者为满
  2. 空队列条件:rear == front
  3. 满队列条件:( rear + 1 ) % maxSize = front
public class CircleArrayQueue {

private int maxSize;
private int[] queue;
private int front; //队首
private int rear; //队尾
/* 说明:
1、为什么环形队列需要预留一个空间:如果不预留,当 front=rear 时不能判断为空还是队满
2、将 front 和 rear 的初始值都设为0,且 rear 永远指向最后一个元素的后一个位置。浪费的空间是rear所在位置
*/
public CircleArrayQueue(int maxSize){
this.maxSize = maxSize;
this.queue = new int[maxSize];
}

public boolean isFull(){
return (rear+1) % maxSize == front;
}

public boolean isEmpty(){
return rear==front;
}

// 入队
public void add(int value){
if(isFull()){
System.out.println("环形队列已满");
return;
}
queue[rear] = value;
rear = (rear + 1) % maxSize;
}

// 出队
public int get(){
if(isEmpty()){
throw new RuntimeException("环形队列为空");
}
int value = queue[front];
front = (front + 1) % maxSize;
return value;
}

// 队列大小
public int size(){
return (rear + maxSize - front) % maxSize;
}

// 查看队首,不出队
public int head(){
if(isEmpty()){
throw new RuntimeException("环形队列为空");
}
return queue[front];
}

// 遍历队列
public void show(){
if(isEmpty()){
throw new RuntimeException("环形队列为空");
}
for(int i = front; i < front+size(); i++){
System.out.printf("arr[%d]=%d\n", i % maxSize, queue[i % maxSize]);
}
}
}

测试代码:

public class Test {

public static void main(String[] args){
// 环形队列
CircleArrayQueue circleArrayQueue = new CircleArrayQueue(3);
circleArrayQueue.add(1);
System.out.println("size:"+circleArrayQueue.size());
circleArrayQueue.add(2);
System.out.println("size:"+circleArrayQueue.size());
circleArrayQueue.get();
System.out.println("size:"+circleArrayQueue.size());
circleArrayQueue.add(3);
System.out.println("size:"+circleArrayQueue.size());
circleArrayQueue.show();
}
}