代码如下:
public class CircleQueue {
//初始化数组的长度,用来判断
private int maxSize;
//起始索引
private int front;
//结束索引
private int rear;
//初始数组
private int[] arr;
//初始化参数
public CircleQueue (int maxSize){
this.maxSize = maxSize;
arr = new int[maxSize];
front = 0;
rear = 0;
}
public boolean isEmpty () {
return rear == front;
}
//因为rear和front一直是紧挨着的
//所以只要rear+1就应该是front
//所以算法是(rear+1)%maxSize==front
public boolean isFull () {
return (rear + 1) % maxSize == front;
}
public void add (int n) {
if(isFull()){
System.put.prinln("queue is full.");
return;
}
//直接将数据加入
arr[rear] = n;
//将rear后后移
rear = (rear + 1) % maxSize;
}
public int get () {
if(isEmpty()){
System.put.prinln("queue is empty.");
return;
}
int result = arr[front];
front = (front + 1) % maxSize;
return result;
}
//显示队列所有数据
public void show () {
if(isEmpty){
System.out.println("empty");
return;
}
//假设maxSize=5,fron=2,rear=0
//这确实是对的
for(int i = front; i <front + size();i++){
System.out.printf("arr[%d]=%d/t",i%maxSize,arr[i%maxSize]);
}
}
public int size () {
return (rear + maxSize - front) % maxSize;
}
}
关注点:
(1)(rear + maxSize - front) % maxSize用来求有效元素个数
(2) i <front +((rear + maxSize - front) % maxSize)控制循环次数
(3)数组需要消耗一个空间来作为rear指向