介绍
使用数组模拟出环形队列
- 分析:尾索引的下一个为头索引时表示队列满,即将队列容量空出一个作为约定,这个在做判断队列满的时候需要注意
- (rear + 1 ) % maxSize == front 满
- rear == front 空
- (rear+maxSize-front)%maxSize 当前队列元素
- 分析示意图:
- 代码实现
package com.atai.exer;
/**
* @author
* @create
*/
public class Queue {
private int maxSize; // 表示数组的最大容量
//front 变量的含义做一个调整: front 就指向队列的第一个元素, 也就是说 arr[front] 就是队列的第一个元素
//front 的初始值 = 0
private int front;
//rear 变量的含义做一个调整:rear 指向队列的最后一个元素的后一个位置. 因为希望空出一个空间做为约定.
//rear 的初始值 = 0
private int rear; // 队列尾
private int[] arr; // 该数据用于存放数据, 模拟队列
public Queue(int maxSize){
this.maxSize=maxSize;
this.arr=new int[maxSize];
}
// 判断队列是否满
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+1)%maxSize;
}
// 获取队列的数据, 出队列
public int getQueue() {
if (isEmpty()){
// 通过抛出异常
throw new RuntimeException("队列空,不能取数据");
}
int temp =front;
front=(front+1)%maxSize;
return arr[temp];
}
// 显示队列的所有数据
public void showQueue() {
// 判断
if (isEmpty()) {
System.out.println("队列空的,没有数据~~");
}
for (int i=front;i<front+((rear+maxSize-front)%maxSize);i++){
System.out.printf("arr[%d]=%d\n",i%maxSize,arr[i%maxSize]);
}
}
// 显示队列的头数据, 注意不是取出数据
public int headQueue() {
// 判断
if (isEmpty()) {
throw new RuntimeException("队列空的,没有数据~~");
}
return arr[front];
}
}