环形队列
- 数组模拟队列的优化,充分利用数组. 因此将数组看做是一个环形的。(通过取模的方式来实现即可)
优化思路
- front变量的含义做一个调整:front就指向队列的第一个元素,也就是说arr[front]就是队列的第一个元素,front的初始值为0
- rear变量的含义做一个调整:rear指向队列的最后一个元素的后一个位置,因为希望留出一个空间做为约定,队列的有效数据个数为maxsize-1,rear的初始值为0
- 此前队列满时,条件是
rear == maxSize - 1
,调整过后,条件变为(rear+1)%maxSize == front
- 当队列尾空时,条件为
rear == front
- 这样调整之后,队列中有效的数据的个数
(rear + maxSize - front) % maxSize
- 根据以上思路进行修改后,就可以得到一个环形队列
环形队列的Java实现
package com.jason.queue;
import java.util.Scanner;
public class CircleArrayQueueDemo {
public static void main(String[] args) {
System.out.println("测试环形队列:");
CircleArrayQueue circleArrayQueue = new CircleArrayQueue(4);
char key = ' ';
Scanner scanner = new Scanner(System.in);
boolean loop = true;
while (loop) {
System.out.println("s(show): 显示队列");
System.out.println("e(exit): 退出程序");
System.out.println("a(add): 添加数据到队列");
System.out.println("g(get): 从队列取出数据");
System.out.println("h(head): 查看队列头的数据");
key = scanner.next().charAt(0);
switch (key) {
case 's':
circleArrayQueue.showQueue();
break;
case 'e':
scanner.close();
loop = false;
break;
case 'a':
System.out.println("请输入一个数");
int n = scanner.nextInt();
circleArrayQueue.addQueue(n);
break;
case 'g':
try {
int res = circleArrayQueue.getQueue();
System.out.printf("取出的数据为%d\n",res);
} catch (Exception e){
e.printStackTrace();
}
break;
case 'h':
try {
int res = circleArrayQueue.headQueue();
System.out.printf("队列头的数据为%d\n",res);
} catch (Exception e){
e.printStackTrace();
}
break;
default:
break;
}
}
System.out.println("程序退出");
}
}
class CircleArrayQueue {
private int maxSize;
private int front;
private int rear;
private int[] arr;
public CircleArrayQueue (int arrMaxSize) {
maxSize = arrMaxSize;
arr = new int[maxSize];
}
public boolean isFull() {
return (rear + 1) % maxSize == front;
}
public boolean isEmpty() {
return front == rear;
}
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 = arr[front];
front = (front + 1) % maxSize;
return temp;
}
public void showQueue() {
if (isEmpty()) {
System.out.println("队列已空,无法取出数据");
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];
}
}