思路:
- 1.front变量的含义做一个调整:front就指向队列的第一个元素也就是说,也就是说arr[front]就是队列的第一个元素
- 2.rear变量的含义做一个调整:rear指向队列的最后一个元素的后一个位置,因为希望空出一个空间作为约定。
- 3.当队列满时,条件是(rear+1)%maxSize==front
- 4.对队列为空的条件,rear==front空
- 5.当我们这样分析,队列中的有效数据的个数(rear+maxSize-front)%maxSize
- 6.我们就可以在原来的队列修改得到环形队列
分析:
尾索引的下一个为头索引时表示队列满,即将队列容量空出一个作为约定,这个在做判断队列满的适合需要注意(rear+1)%maxSizefront为满,rearfront为空
代码
class CircleArray{
private int maxSize;//数组最大容量
private int front;//指向队列的第一个元素,也就是说arr[front]
private int rear;//rear指向队列的最后一个元素的后一个位置,也就是预留空白位置
private int arr[];//该数组用于模拟队列
//创建队列的构造器
public CircleArray(int arrMaxSize){
maxSize=arrMaxSize;
arr=new int[maxSize];
front=0;
rear=0;
}
//判断队列是否满
public boolean isFull(){
return (rear+1)%maxSize==front;
}
//判断队列是否为空
public boolean isEmpty(){
return rear==front;
}
//添加数据到队列
public void addQueue(int n){
//判断队列是否满
if(isFull()){
System.out.println("队列满,无法加入");
return;
}
//直接将数据加入
arr[rear]=n;
//将rear后移
rear=(rear+1)%maxSize;
}
//获取队列的数据,出队列
public int getQueue(){
//判断队列是否空
if(isEmpty()){
//通过抛出异常
throw new RuntimeException("队列空,不能取数据");
}
//front是指向队列的第一个元素
//1.先把front对应的值保存到一个临时变量
//2.将front后移
//3.将临时的变量保存
int value=arr[front];
front=(front+1)%maxSize;
return value;
}
//求出当前队列的有效数据
public int size(){
return (rear+maxSize-front)%maxSize;
}
//显示队列的所有数据
public void showQueue(){
//遍历
if(isEmpty()){
System.out.println("队列空,没有数据");
return;
}
//思路:从front开始遍历,开始遍历多少个元素
for (int i = front; i <front+size();i++ ) {
System.out.println("\t"+arr[i%maxSize]);
}
}
//显示队列的头数据
public int headQueue(){
if (isEmpty()){
throw new RuntimeException("队列空,没有数据");
}
return arr[front];
}
}