队列
什么是队列
说到队列,自然会想到现实中说的队列,例如“打饭排队”,“车队”,他们都是从一端进行入队,也就是排队的队尾,一端进行出队,也就是排队的队头,而且是先入队的先出队。
队列的特点
先进先出,一端进一端出。
队列的使用场景
①树的层次遍历
②图的广度优先遍历(DFS)
③操作系统中的先来先服务原则
以上三个都是队列常见的使用场景
代码实现
用数组模拟一个队列
package com.practise.arrayqueue;
import java.lang.reflect.Array;
import java.sql.SQLOutput;
import java.util.Scanner;
public class ArrayQueue {
//队列数据数组
int arr[];
//头指针
int front;
//尾指针
int rear;
//队列最大长度
int maxSize;
//构造函数,传入队列最大值
public ArrayQueue(int arrMaxSize) {
maxSize = arrMaxSize;
arr = new int[maxSize];
front = -1;
rear = -1;
}
//判断队满
public boolean isFull(){
//队尾指针=maxsize-1
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];
}
public static void main(String[] args) {
ArrayQueue arrayQueue = new ArrayQueue(10);
//用户输入
char key = ' ';
//创建Scanner
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 'a':
System.out.println("请输入一个数");
int value = scanner.nextInt();
arrayQueue.addQueue(value);
break;
case 'g':
try{
int res = arrayQueue.getQueue();;
System.out.printf("取出的数据是:%d\n",res);
}catch (Exception e){
System.out.println(e.getMessage());
}
break;
case 'h':
try {
int res = arrayQueue.headQueue();
System.out.printf("头部的数据是:%d\n",res);
}catch (Exception e){
System.out.println(e.getMessage());
}
break;
case 'e':
scanner.close();
loop = false;
break;
default:
break;
}
}
System.out.println("程序退出-----");
}
}