public class ArrayQueueDemo {
public static void main(String[] args) {
ArrayQueue arrayQueue = new ArrayQueue(5);
char key;
Scanner scanner = new Scanner(System.in);
a:while (true) {
try {
System.out.println("q:退出程序");
System.out.println("s:查看队列");
System.out.println("a:向队列中加值");
System.out.println("g:从队列中取值");
System.out.println("h:查看队首元素");
key = scanner.next().charAt(0);
switch (key) {
case 's':
arrayQueue.showQueue();
break;
case 'a':
System.out.println("输入一个值");
arrayQueue.addQueue(scanner.nextInt());
break;
case 'g':
System.out.println("从队列中取出的值为" + arrayQueue.getQueue());
break;
case 'h':
System.out.println("队首元素为" + arrayQueue.queueHead());
break;
case 'q':
scanner.close();
System.out.println("退出程序");
break a;
default:
System.out.println("命令错误");
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
}
class ArrayQueue {
private int maxSize; // 队列的最大容量
private int front; // 队列头指针 指向队列头的前一个位置
private int rear; // 队列尾指针 指向队列的最后一个位置
private int[] array; // 数组
public ArrayQueue(int arrayMaxSize) {
// 初始化队列
this.maxSize = arrayMaxSize;
this.array = new int[maxSize];
this.front = -1; // 指向队列头的前一个位置
this.rear = -1; // 指向队列的最后一个位置
}
public boolean isFull() {
return rear == maxSize - 1; // 判断队列是否已满
}
public boolean isEmpty() {
return front == rear; // 判断队列是否为空
}
public void addQueue(int value) {
if (this.isFull()) {
throw new RuntimeException("队列已满");
}
this.rear++;// 赋值必须先加后用
array[this.rear] = value;
}
public int getQueue() {
if (this.isEmpty()) {
throw new RuntimeException("队列为空");
}
this.front++; // 取值必须先加后用
return array[this.front];
}
public void showQueue() {
if (this.isEmpty()) {
throw new RuntimeException("队列为空");
}
for (int i = this.front + 1; i <= this.rear; i++) {
System.out.printf("arr[%d]=%dtn",i,this.array[i]); // 显示队列中的数据
}
}
public int queueHead() {
if (this.isEmpty()) {
throw new RuntimeException("队列为空");
}
return this.array[front + 1]; // 显示队首元素 不能使用++ 不改变队首指针
}
}