队列是一个有序列表,可以用数组或者链表实现,遵循先进先出原则,先存入数据先取出,后存入后取出。
以下是一个数据结构为数组的简单环形队列案例:
/**
* @author maoyouhua
* @version jdk21
* 数组队列 遵循先进先出的原则
* 环形队列
*/
public class ArrayQueue {
private int size; //队列元素个数
private int front; //队列头
private int rear; //队列尾
private final int[] arr; //数组
public ArrayQueue(int size) {
arr = new int[size];
// front = 0; //指向队列头
// rear = 0; //指向队列尾
}
/**
* 判断队列是否已满
*/
public boolean isFull(){
return size == arr.length;
}
/**
* 判断队列是否为空
*/
public boolean isEmpty(){
return size == 0;
}
/**
* 入队
*/
public void addQueue(int n){
if (isFull()) {
System.out.println("队列已满,不能添加数据");
return;
}
arr[rear] = n;
rear = (rear + 1) % arr.length;
size++;
}
/**
* 出队
*/
public int getQueue(){
if (isEmpty()) {
throw new RuntimeException("队列为空,不能取出数据");
}
int element = arr[front];
front = (front + 1) % arr.length;
size--;
return element;
}
/**
* 遍历
*/
public void showQueue(){
if (isEmpty()) {
throw new RuntimeException("队列为空不能遍历数据");
}
for (int i = 0; i < size; i++) {
System.out.println("队列元素:" + arr[(front + i) % arr.length]);
}
}
/**
* 展示队列头
*/
public void headQueue(){
if (isEmpty()) {
throw new RuntimeException("队列为空,没有数据");
}
System.out.println("队列头的第一个元素是:" + arr[front]);
}
/**
* 返回队列的元素个数
*/
public int size(){
return size;
}
public static void main(String[] args) {
ArrayQueue arrayQueue = new ArrayQueue(3);
arrayQueue.addQueue(2);
arrayQueue.addQueue(3);
arrayQueue.addQueue(4);
arrayQueue.showQueue();
System.out.println("-------------");
arrayQueue.getQueue();
arrayQueue.getQueue();
arrayQueue.addQueue(5);
arrayQueue.addQueue(6);
arrayQueue.showQueue();
arrayQueue.headQueue();
arrayQueue.showQueue();
System.out.println("队列元素个数是:" + arrayQueue.size());
}
}