package com.queue;
/* 队列基本介绍:
* 1、队列是一个有序列表,可以用数组或链表来实现
* 2、遵循先入先出的原则,即:县存入队列的数据,要先取出,后存入的要 后取出
*
* 数组模拟环形队列基本思路:
* 1、front变量的含义做一个调整,front指向队列第一个元素,也就是说arr[front]就是队列的第一个元素
* 2、rear的变量的含义做一个调整,rear指向队列的最后一个元素的后一个位置,因为希望空出一个空间作为约定
* 3、当队列满时,条件是:(rear+1)%maxSize==front
* 4、队列为空的条件:rear == front为空
* 5、front的初始值为front=0,rear的初始值rear=0
* 6、当我们这样分析,队列中有效的数据的个数为:(rear+maxSize-front)%maxSize
*/
//使用数组模拟对队列编写一个ArrayQueue类
class CircleArrayQueue
{
private int maxSize; // 表示数组的最大容量
//front指向队列第一个元素,也就是说arr[front]就是队列的第一个元素
private int front;// 队列头
//rear指向队列的最后一个元素的后一个位置,因为希望空出一个空间作为约定
private int rear;// 队列尾
private int[] arr;// 该数组用于存放数据,模拟队列
public CircleArrayQueue(int arrMaxSize)
{
this.maxSize=arrMaxSize;
arr=new int[this.maxSize];
front=0;//front指向队列第一个元素,也就是说arr[front]就是队列的第一个元素
rear=0;//rear指向队列的最后一个元素的后一个位置,因为希望空出一个空间作为约定
}
//判断队列是否满
public boolean isFull()
{
return (this.rear+1)%this.maxSize==this.front;
}
//判断队列是否为空
public boolean isEmpty()
{
return this.rear == this.front;
}
//添加数据到队列
public void addQueue(int n)
{
//判断队列是否为空
if(this.isFull())
{
System.out.println("队列满,不能加入数据~");
return;
}
this.arr[this.rear]=n;
//将rear后移
this.rear=(this.rear+1)%this.maxSize;
}
//获取队列的数据,出队列
public int getQueue()
{
//判断队列是否为空
if(this.isEmpty())
{
// 通过抛出异常处理
throw new RuntimeException("队列空,不能取数据");
}
//这里需要分析出front是指向队列的第一个元素
//1、先把front对应的值保留到一个临时变量
//2、将front后移
//3.将临时保存的变量返回
int value=this.arr[this.front];
this.front=(this.front+1)%this.maxSize;
return value;
}
//求出当前队列有效数据的个数
public int size()
{
return (this.rear+this.maxSize-this.front)%this.maxSize;
}
//显示队列的所有数据
public void showQueue()
{
if(this.isEmpty())
{
System.out.println("队列为空,没有数据");
return;
}
//思路:从front开始遍历,遍历多个元素
//
for(int i=this.front;i<this.front+this.size();i++)
{
System.out.printf("arr[%d]=%d\n",i%this.maxSize,arr[i%this.maxSize]);
}
System.out.println();
}
//显示队列的头数据,不是取数据
public int headQueue()
{
//判断队列是否为空
if(this.isEmpty())
{
throw new RuntimeException("队列为空,没有数据");
}
return this.arr[this.front];
}
}
public class ArrayCircleQueueDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
CircleArrayQueue arrq = new CircleArrayQueue(5);
arrq.showQueue();
arrq.addQueue(10);
arrq.addQueue(20);
arrq.addQueue(30);
arrq.addQueue(40);
arrq.addQueue(50);
arrq.showQueue();
int value=arrq.getQueue();
System.out.printf("get value is %d\n",value);
int head=arrq.headQueue();
System.out.printf("head of queue is %d\n",head);
arrq.addQueue(60);
arrq.showQueue();
value=arrq.getQueue();
System.out.printf("get value is %d\n",value);
value=arrq.getQueue();
System.out.printf("get value is %d\n",value);
arrq.addQueue(70);
arrq.showQueue();
arrq.addQueue(80);
arrq.showQueue();
}
}
运行结果如下:
队列为空,没有数据
队列满,不能加入数据~
arr[0]=10
arr[1]=20
arr[2]=30
arr[3]=40
get value is 10
head of queue is 20
arr[1]=20
arr[2]=30
arr[3]=40
arr[4]=60
get value is 20
get value is 30
arr[3]=40
arr[4]=60
arr[0]=70
arr[3]=40
arr[4]=60
arr[0]=70
arr[1]=80