使用数组模拟队列-编写一个ArrayQueue类
package com.zhaomx.demo.algorithm.queue;
public class ArrayQueueDemo {
public static void main(String[] args) {
ArrayQueue arrayQueue = new ArrayQueue(4);
arrayQueue.add(1);
arrayQueue.add(3);
arrayQueue.add(2);
arrayQueue.add(15);
arrayQueue.showAll();
int result = arrayQueue.get();
System.out.printf("顺序取队列数据:%d\n", result);
}
}
class ArrayQueue {
private int maxSize;
private int front;
private int rear;
private int[] arr;
public ArrayQueue(int arrMaxSize) {
this.maxSize = arrMaxSize;
this.arr = new int[maxSize];
this.front = -1;
this.rear = -1;
}
public boolean isFull() {
return rear == maxSize - 1;
}
public boolean isEmpty() {
return rear == front;
}
public void add(int n) {
if (isFull()) {
throw new RuntimeException("队列已满");
}
rear++;
arr[rear] = n;
}
public int get() {
if (isEmpty()) {
throw new RuntimeException("队列为空,无法获取数据");
}
front++;
return arr[front];
}
public void showAll() {
if (isEmpty()) {
System.out.println("队列为空");
return;
}
for (int i = 0; i < arr.length; i++) {
System.out.printf("arr[%d]=%d\n", i, arr[i]);
}
}
public int head() {
if (isEmpty()) {
throw new RuntimeException("队列为空");
}
return arr[front + 1];
}
}