队列
先进先出
1 数组模拟环形队列
public class ArrayQueue {
//定义队列
private int maxSize;
private int front;//指向第一个元素
private int rear;//指向最后一个元素的后一个位置
private int[] arr;
//构造器
public ArrayQueue(int maxSize) {
this.maxSize = maxSize;
this.arr = new int[maxSize];
}
//判断是否为满,
public boolean isFull() {
return (this.rear + 1) % this.maxSize == this.front;
}
//判断是否为空
public boolean isEmpty() {
return this.rear == this.front;
}
//入队
public void pushQueue(int n) {
//判满
if (this.isFull()) {
System.out.println("Full Queue!");
return;
}
//从尾部入队
this.arr[this.rear] = n;
this.rear = (this.rear + 1) % this.maxSize;
}
//出队
public int popQueue() {
//判空
if (isEmpty()) {
throw new RuntimeException("Empty Queue!");
}
int temp = this.arr[this.front];
this.front = (this.front + 1) % this.maxSize;
return temp;
}
//有效数据个数
public int size() {
return (this.rear + this.maxSize - this.front) % maxSize;
}
//显示
public void showQueue() {
if (this.isEmpty()) {
System.out.println("Empty Queue!");
return;
}
for (int i = this.front; i < this.front + this.size(); i++) {
System.out.printf("arr[%d] = %d\n", i % this.maxSize, this.arr[i % this.maxSize]);
}
}
//显示队头
public int getHead() {
if (isEmpty()) {
throw new RuntimeException("Empty Queue!");
}
return this.arr[this.front];
}
}