我们将数据存入队列时称为"addQueue", "addQueue"的处理需要有两个步骤:
(1)将指针往后移:rear + 1 当 front == rear 时,此时队列为空
(2)若尾指针 rear 小于队列的最大下标 maxSize - 1,则将数据存入 rear 所指的数组元素中,否则无法存入数据,rear == maxSize -1时,队列已满
代码实现:
import java.util.Scanner;
public class ArrayQueueDemo {
public static void main(String[] args) {
ArrayQueue queue = new ArrayQueue(5);
boolean loop = true;
char key = ' '; // 接收用户的输入
Scanner scanner = new Scanner(System.in);
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':
try{
queue.showQueue();
} catch (Exception e){
System.out.println(e.getMessage());
}
break;
case 'e':
System.out.println("程序即将退出,再见~~");
loop = false;
break;
case 'a':
try{
System.out.print("请输入要添加的数据:");
int value = scanner.nextInt();
queue.addQueue(value);
} catch (Exception e){
System.out.println(e.getMessage());
}
break;
case 'g':
try{
int value = queue.getQueue();
System.out.println(value);
} catch (Exception e){
System.out.println(e.getMessage());
}
break;
case 'h':
try{
queue.showHead();
} catch (Exception e){
System.out.println(e.getMessage());
}
break;
default:
break;
}
}
}
}
class ArrayQueue{
private int maxSize;
private int front;
private int rear;
private int [] array;
/* 创建队列的构造器 */
public ArrayQueue(int arrSize){
maxSize = arrSize;
array = new int[maxSize];
front = -1;
rear = -1;
}
/* 判断队列是否为空 */
public boolean isEmpty(){
return front == rear;
}
/* 判断队列是否已满 */
public boolean isFull(){
return rear == maxSize - 1;
}
// 展示队列的首个数据
public void showHead(){
if (isEmpty()){
throw new RuntimeException("当前队列为空!!!没有数据~~");
}
System.out.println("当前队列首个元素为" + array[front + 1]);
}
// 取出队列数据
public int getQueue(){
// 判断队列是否为空
if(isEmpty()){
throw new RuntimeException("当前队列为空!!!,没有数据~");
}
return array[++front];
}
// 向队列添加数据
public void addQueue(int value){
// 判断队列是否已满
if(isFull()){
throw new RuntimeException("当前队列已满,无法添加数据");
}
rear++;
array[rear] = value;
}
// 展示队列
public void showQueue(){
if(isEmpty()){
throw new RuntimeException("当前队列为空,没有数据~~");
}
for (int i = front + 1; i <= rear ; i++) {
System.out.printf("arr[%d] = %d\n", i, array[i]);
}
}
}
此时代码存在一个漏洞:即数组模拟队列,只能用一次,无法达到复用的效果