环形队列
队列:先进先出,类似于排队服务,先来的人排在前面,后来的人排在后面,按照排队顺序享受服务;
PS:但是队列只能用一次,可以优化成环形队列重复使用空间
- 变量front:指向环形队列的头部;
- 变量rear:指向环形队列尾部的后一个位置;
- 变量maxSize:环形队列长度;
- 环形队列为空:front = rear
- 环形队列为满:(rear + 1)% maxSize = front
- 环形队列已利用的空间:(rear + maxSize - front)% maxSize
class CircleQueue
{
private int front; //指向环形数组的头部
private int rear; //指向环形数组尾部的后一个位置
private int [] arr; //用数组模拟环形队列
private int maxSize; //数组长度
public CircleQueue(int arrLen) //构造函数
{
this.maxSize = arrLen;
this.arr = new int [arrLen];
}
public boolean isEmpty() //判断环形队列是否为空
{
return front == rear;
}
public boolean isFull() //判断环形队列是否为满
{
return (rear + 1) % maxSize == front;
}
public int size() //返回环形队列已利用的空间
{
return (rear + maxSize - front) % maxSize;
}
public void addQueue(int num) //入队
{
if (isFull())
{
throw new RuntimeException("循环队列已满,不能继续添加数据!");
}
else
{
arr[rear] = num;
rear = (rear + 1) % maxSize;
}
}
public int getQueue() //出队
{
if (isEmpty())
{
throw new RuntimeException("循环队列已空,不能继续删除数据");
}
else
{
int value = arr[front];
front = (front + 1) % maxSize;
return value;
}
}
public void showQueue() //查看环形队列里面所有的值
{
if (isEmpty())
{
throw new RuntimeException("循环队列已空,没有任何数据");
}
else
{
int sum = front + size();
for (int i = front; i < sum; i++)
{
System.out.printf("arr[%d] = %d\n", i % maxSize, arr[i % maxSize]);
}
}
}
}