20210329-算法学习-队列(环形队列)
1.数组模拟环形队列:
对之前的(数组模拟队列)进行优化,充分利用数组,因此将数组看做一个环形(通过取模的方式来实现)
1.1.思路:
首先对front变量的含义做一个调整:front初始值为0,就是指向队列的第一个元素,也就是 arr[front]就是第一个元素
rear的含义做一个调整:rear初始值为0,就是指向队列的最后一个元素的后一个位置,因为希望空出一个空间作为约定
当队列满时,条件时(rear+1)%maxSize == front
当队列空时,条件时 rear == front
当这样分析,队列中的元素个数为(rear+maxSize-front)%maxSize
1.2注意:
尾索引的下一个为头索引时表示队列满,即将队列容量空出一个作为约定,(在做判断队列满时需要注意)
1.3.示意图:
图1.1
2.代码:
package com.atAlgorithmTest;
/**
* @Author: lisongtao
* @Date: 2021/3/29 20:11
*/
import java.util.Scanner;
/**
* @ClassName QueueArrayCirele
* @Description环形队列
* @Author DELL
* @Date 2021/03/29 20:11
**/
public class QueueArrayCirele {
public static void main(String[] args) {
System.out.println("测试数组模拟环形队列");
ArrayCirele arrayCirele = new ArrayCirele(5);
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':
arrayCirele.showQueue();
break;
case 'a':
System.out.println("输入一个数字");
int value = scanner.nextInt();
arrayCirele.addQueue(value);
break;
case 'g'://取出数据
try {
int res = arrayCirele.getQueue();
System.out.printf("取出的数据是%d\n",res);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'h'://查看队列头数据
try {
int res = arrayCirele.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("程序退出");
}
}
//创建,一个数组模拟环形队列
class ArrayCirele{
private int maxSize;//数组的最大容量
//front 变量的含义做一个调整,front就指向队列的第一个元素,也就是说arr[front] 就是队列的第一个元素
//front 的初始值 = 0
private int front;//队列头
private int rear;//队列尾
private int arr[];//用于存放数据,模拟队列
//创建队列构造器
public ArrayCirele(int arrMaxSize){
maxSize = arrMaxSize;
arr = new int[maxSize];
}
//判断队列是否已满
public boolean isFull(){
return (rear+1)%maxSize==front;
}
//判断队列是否为空
public boolean isEmpty(){
return rear==front;
}
//添加数据到队列中
public void addQueue(int n){
//判断队列是否已满
if (isFull()){
System.out.println("队列已满,不能加入数据");
return;
}
//直接将数据加入
arr[rear] = n;
//将 rear后移,这里(必须考虑取模)
rear = (rear+1)%maxSize;
}
//获取队列的数据,出 队列
public int getQueue(){
//出列是判断队列是否为空
if(isEmpty()){
throw new RuntimeException("队列空,不能取数据");
}
//这里需要分析出 front是指向队列的第一个元素
//1.先把 front对应的值保留一个临时变量中
//2.将front后移,考虑取模
//3.将临时保存的变量返回
int value = arr[front];
front = (front+1)%maxSize;
return value;
}
//显示队列中所有数据
public void showQueue(){
//遍历
if (isEmpty()){
System.out.println("队列空,没有数据");
return;
}
for (int i = front;i<front+size();i++){
System.out.printf("arr[%d]=%d\n",i%maxSize,arr[i%maxSize]);
}
}
//求出当前队列有效个数
public int size(){
return (rear+maxSize-front)%maxSize;
}
//显示队列的头数据,注意不是取出数据
public int headQueue(){
//判断
if (isEmpty()){
throw new RuntimeException("队列空,没有数据");
}
return arr[front];
}
}

浙公网安备 33010602011771号