使用数组模拟环形队列
思路:front和rear分别为队首和对尾+1,且初始值均为0。使用一个空闲元素作为标记位置,将栈空和栈满的情况区分。
public class CircleArrQueue {
public static void main(String[] args) {
CircleArrayQueue circleArrayQueue = new CircleArrayQueue(3);
//测试方法
circleArrayQueue.addQueue(1);
circleArrayQueue.addQueue(2);
circleArrayQueue.addQueue(3);
circleArrayQueue.showQueue();
System.out.println("----------------------------");
System.out.println(circleArrayQueue.getQueue());
System.out.println(circleArrayQueue.headQueue());
circleArrayQueue.showQueue();
System.out.println("----------------------------");
circleArrayQueue.addQueue(4);
System.out.println(circleArrayQueue.isFull());
System.out.println(circleArrayQueue.addQueue(6));
System.out.println("----------------------------");
System.out.println(circleArrayQueue.getQueue());
System.out.println(circleArrayQueue.getQueue());
System.out.println(circleArrayQueue.getQueue());
// System.out.println(circleArrayQueue.getQueue()); //Exception 队列为空,无法删除
System.out.println(circleArrayQueue.isEmpty());
System.out.println("----------------------------");
}
}
class CircleArrayQueue {
private int maxSize;//最大容量(需要一个空位置进行标记)
private int front;//队头元素
private int rear;//队尾元素的后一个位置
private int[] arr;//该数组用于存放数据,模拟队列
public CircleArrayQueue(int maxSize) {
this.maxSize = maxSize + 1;
this.front = 0;
this.rear = 0;
this.arr = new int[maxSize + 1];
}
/**
* @return 判断队列是否满
*/
public boolean isFull() {
return (rear + 1) % maxSize == front;
}
/**
* @return 判断队列是否为空
*/
public boolean isEmpty() {
return front == rear;
}
/**
* 添加数据到队列
*
* @param n 加入队列的值
* @return 是否添加成功
*/
public boolean addQueue(int n) {
//判断队列是否为满
if (isFull())
return false;
arr[rear] = n;
rear = (rear + 1) % maxSize;
return true;
}
/**
* @return 出队列
*/
public int getQueue() {
if (isEmpty())
throw new RuntimeException("队列为空");
int val = arr[front];
front = (front + 1) % maxSize;
return val;
}
/**
* 显示队列现有元素
*/
public void showQueue() {
if (isEmpty()) {
System.out.println("队列为空");
}
for (int i = front; i < front + getSize(); i++)
System.out.println(arr[i % maxSize]);
}
/**
* 显示队列头元素
*/
public int headQueue() {
if (isEmpty())
throw new RuntimeException("队列为空");
return arr[front];
}
/**
* 获取队列有效元素个数
*
* @return 元素个数
*/
public int getSize() {
return (rear + maxSize - front) % maxSize;
}
}