队列介绍
- 队列是一个有序列表,可以用数组或是链表来实现。
- 遵循先入先出的原则。即:先存入队列的数据,要先取出。后存入的要后取出
示意图:(使用数组模拟队列示意图)
数组模拟队列
- 队列本身是有序列表,若使用数组的结构来存储队列的数据,则队列数组的声明如下图, 其中 maxSize 是该队列的最大容量。
- 因为队列的输出、输入是分别从前后端来处理,因此需要两个变量 front及 rear分别记录队列前后端的下标,front
会随着数据输出而改变,而 rear则是随着数据输入而改变,如图所示:
思路分析
当我们将数据存入队列时称为”addQueue”,addQueue 的处理需要有两个步骤:
- 将尾指针往后移:rear+1 , 当front == rear 【空】
- 若尾指针 rear 小于队列的最大下标 maxSize-1,则将数据存入 rear所指的数组元素中,否则无法存入数据。 rear == maxSize - 1[队列满]
代码实现
package com.atguigu.queue;
import java.util.Scanner;
/**
*
* @author: mayu
* @version: 1.0
* @date: 2019/6/4
* @time: 16:34
* @description: 数组模拟队列
* (1):应用场景:银行的叫号排队系统。
* (2):思路分析
* (3):代码实现
*/
public class ArrayQueueDemo {
public static void main(String[] args) {
//测试队列
ArrayQueue queue = new ArrayQueue(3);
char key = ' ';
Scanner scanner = new Scanner(System.in);
boolean loop = true;
while (loop) {
System.out.println("a(add):向队列添加数据!");
System.out.println("g(get):取出队列数据!");
System.out.println("s(show):展示队列所有数据!");
System.out.println("h(head):展示队列头部数据!");
System.out.println("e(exit):退出程序!");
key = scanner.next().charAt(0);
switch (key) {
case 'a':
System.out.println("请输入一个数:");
int nextInt = scanner.nextInt();
try {
queue.addQueue(nextInt);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'g':
try {
int queue1 = queue.getQueue();
System.out.println("取出队列数据为:" + queue1);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 's':
try {
queue.showQueue();
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'h':
try {
int queue1 = queue.headQueue();
System.out.println("队列头部数据为:" + queue1);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'e':
scanner.close();
loop = false;
break;
}
}
System.out.println("程序退出!");
}
}
class ArrayQueue {
private int maxSize;//数组最大容量
private int front;//队列头(指向队列的第一个数据的下标的前一个位置)
private int rear;//队列尾(指向队列的最后一个数据的下标)
private int[] arr;//存放数据的,模拟队列
public ArrayQueue(int maxSize) {
this.maxSize = maxSize;
arr = new int[maxSize];
front = -1;
rear = -1;
}
/**
* 判断队列是否满了
*
* @return
*/
public boolean isFull() {
return rear == maxSize - 1;
}
/**
* 判断队列是否为空
*
* @return
*/
public boolean isEmpty() {
return front == rear;
}
/**
* 往队列加数据
*
* @param n
*/
public void addQueue(int n) {
if (isFull()) {
throw new RuntimeException("对列满了,无法加数据~~");
}
rear++;
arr[rear] = n;
}
/**
* 从队列取数据
*
* @return
*/
public int getQueue() {
if (isEmpty()) {
throw new RuntimeException("队列为空,无法取数据~~");
}
front++;
return arr[front];
}
/**
* 展示队列所有数据
*/
public void showQueue() {
if (isEmpty()) {
throw new RuntimeException("队列为空,无法展示队列数据~~");
}
for (int data : arr
) {
System.out.printf("%d\t\n", data);
}
}
/**
* 获取队列头数据
*
* @return
*/
public int headQueue() {
if (isEmpty()) {
throw new RuntimeException("对列为空,无法取出队列头数据~~");
}
return arr[front + 1];
}
}