


当我们将数据存入队列时称为” addQueue”, addQueue 的处理需要有两个步骤: 思路分析
1)将尾指针往后移: rear
+
1
+1
+1, 当 front
=
=
==
== rear 【空】
2)若尾指针 rear 小于队列的最大下标 maxSize-1, 则将数据存入 rear 所指的数组元素中, 否则无法存入数据。 rear
=
=
max
==\max
==max Size
−
1
-1
−1 [队列满]
public class ArrayQueue {
public static void main(String[] args) {
// 1. 声明数组模拟的队列,设置maxSize为4
ArrayQueue arrayQueue = new ArrayQueue(4);
// 2. 开始测试
arrayQueue.add(1);
arrayQueue.add(3);
arrayQueue.add(4);
arrayQueue.add(2);
arrayQueue.add(5);
System.out.println(arrayQueue.poll());
System.out.println(arrayQueue.poll());
System.out.println(arrayQueue.poll());
System.out.println(arrayQueue.poll());
System.out.println(arrayQueue.poll());
}
// 数组长度(队列的最大容量)
int maxSize;
// 当前队列长度
int curSize;
// 数组
int[] arr;
// 当前指向的元素
int curIndex;
public ArrayQueue(int maxSize) {
this.maxSize = maxSize;
arr = new int[maxSize];
curIndex = 0;
curSize = 0;
}
// 添加元素到队列
public void add(int num) {
if (curSize >= maxSize) {
System.err.println("队列容量不足,无法添加元素");
}else{
arr[curSize++] = num;
}
}
// 从队列取出头元素
public int poll() {
if (curIndex >= curSize) {
throw new RuntimeException("当前队列为空,无法取出元素");
}else if (curIndex >= maxSize) {
throw new RuntimeException("超出队列长度");
}else{
return arr[curIndex++];
}
}
}
输出:
队列容量不足,无法添加元素
1
3
4
2
Exception in thread "main" java.lang.RuntimeException: 当前队列为空,无法取出元素
at com.wskh.DataStructures.Queue.ArrayQueue.poll(ArrayQueue.java:57)
at com.wskh.DataStructures.Queue.ArrayQueue.main(ArrayQueue.java:26)
对前面的数组模拟队列的优化, 充分利用数组. 因此将数组看做是一个环形的。(通过取模的方式来实现即可)
分析说明:

public class CircleArrayQueue {
public static void main(String[] args) {
// 1. 声明数组模拟的队列,设置maxSize为4
CircleArrayQueue circleArrayQueue = new CircleArrayQueue(4);
// 2. 开始测试
circleArrayQueue.add(1);
circleArrayQueue.add(3);
circleArrayQueue.add(4);
System.out.println(circleArrayQueue.poll());
System.out.println(circleArrayQueue.poll());
circleArrayQueue.add(2);
circleArrayQueue.add(5);
System.out.println(circleArrayQueue.poll());
System.out.println(circleArrayQueue.poll());
System.out.println(circleArrayQueue.poll());
}
// 数组长度(队列的最大容量)
int maxSize;
// 当前队列长度
int curSize;
// 当前追加的指针
int addIndex;
// 数组
Integer[] arr;
// 当前指向的元素
int curIndex;
public CircleArrayQueue(int maxSize) {
this.maxSize = maxSize;
arr = new Integer[maxSize];
curIndex = 0;
curSize = 0;
addIndex = 0;
}
// 添加元素到队列
public void add(int num) {
if (curSize >= maxSize) {
System.err.println("队列容量不足,无法添加元素");
} else {
arr[(addIndex++) % maxSize] = num;
}
}
// 从队列取出头元素
public int poll() {
if (arr[curIndex % maxSize] == null) {
throw new RuntimeException("当前队列为空,无法取出元素");
} else {
curSize--;
Integer integer = arr[curIndex % maxSize];
arr[curIndex % maxSize] = null;
curIndex++;
return integer;
}
}
}
输出:
1
3
4
2
5