数组模拟队列代码实现(不是环形队列目前只能存取一次)
package com.yuteng.queue;
import java.util.Scanner;
/**
* @version 1.0
* @author: 余腾
* @date: 2021-07-21 10:16
*/
public class ArrayQueueDemo {
public static void main(String[] args) {
ArrayQueue queue = new ArrayQueue(3);
//接受用户输入
char key = ' ';
Scanner sc = 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 = sc.next().charAt(0);
switch (key) {
case 's':
queue.showQueue();
break;
case 'a':
System.out.println("输入一个数字");
int value = sc.nextInt();
queue.addQueue(value);
break;
case 'g':
try {
int res = queue.getQueue();
System.out.printf("取出的数据是%d\n",res);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'h':
try {
int res=queue.headQueue();
System.out.printf("队列头的数据是%d\n",res);
}catch (Exception e){
System.out.println(e.getMessage());
}
break;
case 'e':
sc.close();
loop=false;
}
}
System.out.println("程序退出");
}
}
/**
* 使用数组模拟队列-编写一个ArrayQueue类
*/
class ArrayQueue {
/**
* 表示数组最大容量
*/
private int maxSize;
/**
* 队列头
*/
private int front;
/**
* 队列尾
*/
private int rear;
/**
* 该数据用于存储数据
*/
private int[] arr;
/**
* 创建队列的构造器
*
* @param arrMaxSize 队列的大小
*/
public ArrayQueue(int arrMaxSize) {
maxSize = arrMaxSize;
arr = new int[maxSize];
//指向队列头部,分析front是指向队列头的前一个位置。
front = -1;
//指向队列尾部,指向队列尾的数据(即是队列的最后一个数据)
rear = -1;
}
/**
* 判断队列是否满的
*
* @return
*/
public boolean isFull() {
return rear == maxSize - 1;
}
public boolean isEmpty() {
return rear == front;
}
/**
* 添加数据到队列
*
* @param n 添加的数据
*/
public void addQueue(int n) {
if (isFull()) {
System.out.println("队列满不能加入数据");
return;
}
//rear后移
rear++;
arr[rear] = n;
}
public int getQueue() {
//判断是否为空
if (isEmpty()) {
//通过抛出异常来处理
throw new RuntimeException("队列为空,不能取出数据");
}
front++;
return arr[front];
}
/**
* 显示队列的所有数据
*/
public void showQueue() {
//遍历
if (isEmpty()) {
System.out.println("队列为空,没有数据~~~~~");
}
for (int i = 0; i < arr.length; i++) {
System.out.printf("arr[%d]=%d\n", i, arr[i]);
}
}
/**
* 显示队列的头数据,注意不是取数据
*/
public int headQueue() {
if (isEmpty()) {
throw new RuntimeException("队列为空,没有数据~~~~~");
}
//因为front 是指向头的前一个位置所以+1
return arr[front + 1];
}
}
问题分析与优化
- 目前数组使用一次就不能再用,没有达到复用的效果
- 将这个数组使用算法改进成一个环形的数组达到复用效果 方式取模:%