1.环形队列的定义
为了有优化数组模拟队列,可以充分地利用数组,把数组当作一个环形的。
2.环形队列判断的思路
- 在环形队列中,空出一个尾部空间,则为(rear+1)% maxSize == front作为判断队列是否为满的条件。
- 判断队列为空的条件
- front调整为0,指向队列中的第一个元素
- rear也调整为0,rear指向最后一个元素的后一个元素,当队列满的时候,rear会指向maSize-1的位置
- 有效数据的个数(rear + maxSize - front) % maxSize
3.代码实现
public class CircleArrayQueueDemo {
public static void main(String[] args) {
ArrayQueue queue = new ArrayQueue(4);
char key = ' ';
Scanner sc = new Scanner(System.in);
boolean loop = true;
while (loop) {
System.out.println("s:显示队列");
System.out.println("a:添加数据到队列");
System.out.println("g:取出数据");
System.out.println("h:查看队列头的数据");
System.out.println("e:退出程序");
key = sc.next().charAt(0);
switch (key) {
case 's':
queue.listQueue();
break;
case 'a':
int num = sc.nextInt();
queue.addQueue(num);
;
break;
case 'g':
try {
int res = queue.getQueue();
System.out.println(res);
} catch (Exception e) {
}
break;
case 'h':
try {
int res = queue.headQueue();
System.out.println(res);
} catch (Exception e) {
}
break;
case 'e':
sc.close();
loop = false;
break;
}
}
}
}
class CircleQueue {
private int maxSize;
private int front;
private int rear;
private int[] arr;
public CircleQueue(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()) {
return;
}
// 直接加入
arr[rear] = n;
// rear后移,必须取模
rear = (rear + 1) % maxSize;
}
// 取出数据
public int getQueue() {
if (isEmpty()) {
throw new RuntimeException();
}
int value = arr[front];
front = (front + 1) % maxSize;
return value;
}
// 显示队列数据
public void listQueue() {
if (isEmpty()) {
return;
}
for (int i = front; i < front + size(); i++) {
System.out.printf("arr[%d] = %d\n", i % maxSize, arr[i % maxSize]);
}
}
// 有效数据
public int size() {
return (rear + maxSize - front) % maxSize;
}
// 显示队列头数据,不是取出数据
public int headQueue() {
if (isEmpty()) {
throw new RuntimeException();
}
return arr[front];
}
}
4.总结
这是一个环形队列的的实现方式,因为数组模拟队列的缺点:数组不能重复使用,取出后,前面的位置就没用了,所以对队列进行优化。
5.我的思考
- 至于为什么空出一个尾部空间,其实通俗来讲很好理解就是把一个数组变成环形队列的时候,最末端会和最前端重合,所以空出一个尾部空间确保这部分不会重合。或者原先的下标是0--maxsize-1,先预留一个不放,那就变成了0--maxsize-2,rear指向最后一个元素的下一个位置,其实就是指向maxsize-1,这样就可以解释的通了。
- 至于为什么有效个数是(rear + maxSize - front) % maxSize,在创建数组对象的时候指定了最大空间,所以这样才可以实现环形队列。