public class ArrayQueue {
private int maxSize; // 数组最大容量
private int front; // 队头指针,指向队头元素的前一个位置
private int rear; // 队尾指针,指向队列尾的最后一个位置
private int[] arr; // 用数组存放数据,模拟队列
public ArrayQueue(int arrMaxSize) {
maxSize = arrMaxSize;
arr = new int[maxSize];
front = rear = 0;
}
public boolean isFull() {
return (rear + 1) % maxSize == front;
}
public boolean isEmpty() {
return rear == front;
}
public void addQueue(int n) {
if (isFull()) {
throw new RuntimeException("队列已满,不能加入数据");
}
arr[rear] = n;
rear = (rear + 1) % maxSize;
}
public int getQueue() {
if (isEmpty()) {
throw new RuntimeException("队列空,无法取出数据");
}
front = (front + 1) % maxSize;
return arr[front];
}
public void show() {
if (isEmpty()) {
System.out.println("当前队列为空!");
return;
}
System.out.print("Queue = [");
int temp = front;
for (int i = 0; i < (rear + maxSize - front) % maxSize; i++) {
if (i == (rear + maxSize - front) % maxSize - 1) {
System.out.print(arr[temp]);
} else {
System.out.print(arr[temp] + ", ");
}
temp = (temp + 1) % maxSize;
}
System.out.println(']');
}
public int headQueue() {
if (isEmpty()) {
throw new RuntimeException("队列为空!");
}
return arr[front];
}
}