队列
- 队列是一个有序列表,可以用数组或是链表来实现。
- 遵循先入先出的原则。即:先存入队列的数据,要先取出。后存入的要后取出
使用数组模拟队列
这个实力存在问题,也就是队列只能使用一次,还需要优化
package com.jason.queue;
import java.util.Scanner;
public class ArrayQueueDemo {
public static void main(String[] args) {
// 测试队列
// 创建一个队列
ArrayQueue arrayQueue = new ArrayQueue(3);
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':
arrayQueue.showQueue();
break;
case 'e':
scanner.close();
loop = false;
break;
case 'a':
System.out.println("请输入一个数");
int n = scanner.nextInt();
arrayQueue.addQueue(n);
break;
case 'g':
try {
int res = arrayQueue.getQueue();
System.out.printf("取出的数据为%d\n",res);
} catch (Exception e){
e.printStackTrace();
}
break;
case 'h':
try {
int res = arrayQueue.headQueue();
System.out.printf("队列头的数据为%d\n",res);
} catch (Exception e){
e.printStackTrace();
}
break;
default:
break;
}
}
System.out.println("程序退出");
}
}
// 使用数组模拟队列编写一个ArrayQueue类
class ArrayQueue {
private int maxSize; //表示队列的最大容量
private int front; //队列头
private int rear; //队列尾
private int[] arr; //该数组用于存放数据,模拟队列
// 创建队列的构造器
public ArrayQueue (){
}
public ArrayQueue(int arrMaxSize) {
maxSize = arrMaxSize;
arr = new int[maxSize];
front = -1; //指向队列头部,-1是指front是指向队列头的前一个位置,默认队列无数据
rear = -1; //指向队列尾,指向队列尾的数据,也就是队列的最后一个数据,默认队列无数据
}
// 判断队列是否已满
public boolean isFull() {
return rear == maxSize - 1;
}
// 判断队列是否为空
public boolean isEmpty() {
return front == rear;
}
// 添加数据到队列,入队列
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++; //front后移
return arr[front];
}
// 显示队列的所有数据
public void showQueue() {
// 遍历
if (isEmpty()) {
// 通过抛出异常来返回
System.out.println("队列已空,无法取出数据");
return;
}
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("队列已空,无法取出数据");
}
return arr[front + 1];
}
}