队列
public class Queue {
private int maxSize;
private int front;
private int rear;
private int[] arr;
public Queue(int maxSize) {
this.maxSize = maxSize;
arr = new int[maxSize];
front = -1;
rear = -1;
}
// 判断队列是否满
public boolean isFull() {
return rear == maxSize - 1;
}
// 判断队列是否空
public boolean isEmpty() {
return front == rear;
}
// 入队
public void inQueue(int n) {
if (isFull()) {
throw new RuntimeException("队列已满");
}
arr[++rear] = n;
}
// 出队
public int outQueue() {
if (isEmpty()) {
throw new RuntimeException("队列为空");
}
return arr[++front];
}
// 打印队列
public void show() {
if (isEmpty()) {
throw new RuntimeException("队列为空");
} else {
for (int i : arr) {
System.out.print(i + " ");
}
}
}
}
循环队列
front: arr[front]为队列第一个元素,初始值front = 0 rear:rear指向最后一个元素的后一个位置,初始值rear = 0 队列满:(rear + 1) % maxSize == front 队列为空: rear == front 队列有效数据的个数(rear + maxSize -front) % maxSize
public class LoopQueue {
private int maxSize;
private int front;
private int rear;
private int[] arr;
public LoopQueue(int maxSize) {
this.maxSize = maxSize;
arr = new int[maxSize];
rear = 0;
front = 0;
}
// 判断队列是否满
public boolean isFull() {
return (rear + 1) % maxSize == front;
}
// 判断队列是否空
public boolean isEmpty() {
return rear == front;
}
// 入队
public void inQueue(int n) {
if (isFull()) {
throw new RuntimeException("队列已满");
}
arr[rear] = n;
rear = (rear + 1) % maxSize;
}
// 出队
public int outQueue() {
if (isEmpty()) {
throw new RuntimeException("队列为空");
}
int tmp = arr[front];
front = (front + 1) % maxSize;
return tmp;
}
// 获取队列元素个数
public int getElementCount() {
return (rear + maxSize -front) % maxSize;
}
// 打印队列元素
public void show() {
if (isEmpty()) {
throw new RuntimeException("队列为空");
}
for (int i = front; i < (front + getElementCount()); i++) {
System.out.println(arr[i % maxSize]);
}
}
}