用数组模拟队列
package com.clear.queue;
import java.util.Scanner;
/**
* 用数组模拟队列
*/
public class ArrayQueueDemo {
public static void main(String[] args) {
// 测试
ArrayQueue queue = new ArrayQueue(3);
char key = ' '; // 接收用户输入
Scanner scanner = new Scanner(System.in);
boolean loop = true;
// 输出一个菜单
while (loop) {
System.out.println("s(showQueue):显示队列");
System.out.println("a(addQueue):入队");
System.out.println("g(getQueue):出队");
System.out.println("h(headQueue):取队头元素");
System.out.println("e(exit):退出程序");
key = scanner.next().charAt(0); // 接收一个字符
switch (key) {
case 's':
queue.showQueue();
System.out.println("------------");
break; // 避免case穿透
case 'a':
System.out.println("输入入队元素:");
int value = scanner.nextInt();
queue.addQueue(value);
System.out.println("------------");
break;
case 'g':
try {
System.out.println("出队元素为:" + queue.getQueue());
System.out.println("------------");
} catch (Exception exception) {
System.out.println(exception.getMessage());
}
break;
case 'h':
try {
System.out.println("队头元素为:" + queue.headQueue());
System.out.println("------------");
} catch (Exception exception) {
exception.printStackTrace();
}
break;
case 'e':
scanner.close();
loop = false;
break;
default:
break;
}
}
System.out.println("程序退出");
}
}
/**
* 使用数组模拟队列-缩写一个ArrayQueue
*/
class ArrayQueue {
private int maxSize; // 标识队列最大容量
private int front; // 队列头
private int rear; // 队列尾
private int[] arr; // 该数组用于存放数据,模拟队列
public ArrayQueue(int maxSize) {
this.maxSize = maxSize;
arr = new int[this.maxSize];
front = -1; // 指向队列头部
rear = -1; // 指向队列尾部
}
/**
* 判断队列是否为满
*
* @return
*/
public boolean isFull() {
return rear == maxSize - 1;
}
/**
* 判断队列是否为空
*
* @return
*/
public boolean isEmpty() {
return rear == front;
}
/**
* 添加元素到队列(入队)
*
* @return
*/
public void addQueue(int n) {
// 判断队列是否满
if (isFull()) {
System.out.println("队列满,不能加入");
return;
}
arr[++rear] = n;
}
/**
* 获取队列元素 (出队)
*
* @return
*/
public int getQueue() {
// 判断队列是否空
if (isEmpty()) {
// 通过抛出异常
throw new RuntimeException("队列空,不能出队");
}
return arr[++front];
}
/**
* 显示队列所有数据
*/
public void showQueue() {
if (isEmpty()) {
System.out.println("队列为空");
return;
}
System.out.printf("队列元素为:");
for (int i = 0; i < arr.length; i++) {
System.out.printf("arr[%d] = %d\t", i, arr[i]);
}
System.out.println();
}
/**
* 取队头元素
*
* @return
*/
public int headQueue() {
if (isEmpty()) {
// 通过抛出异常
throw new RuntimeException("队列空,不能取到");
}
return arr[front + 1];
}
}