底层数组实现了一个环形队列
package cn.agan.queue;
import java.util.Scanner;
/**
* 使用数组模拟队列
*/
public class CircularQueueDemo {
public static void main(String[] args) {
//创建一个队列
CircularQueue arrayQueue = new CircularQueue(3);
char key = ' '; //接受用户输入
Scanner scanner = new Scanner(System.in);
boolean loop = true;
while (loop) {
System.out.println("s(show):显示队列");
System.out.println("e(exit):退出程序");
System.out.println("a(add):添加数据到队列");
System.out.println("g(get):从队列中获取数据");
System.out.println("h(head):查看队列头数据");
System.out.println("l(large):查看队列当前包含多少个元素");
System.out.println("=====================");
key = scanner.next().charAt(0);
switch (key) {
case 's':
arrayQueue.showQueue();
break;
case 'a':
System.out.println("输入一个数据");
int value = scanner.nextInt();
arrayQueue.addQueue(value);
break;
case 'g':
try {
int pop = arrayQueue.pop();
System.out.println("获取到的数据为"+pop);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'h':
try {
int pop = arrayQueue.peakQueue();
System.out.println("队列头的数据为"+pop);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'e':
scanner.close();
loop = false;
break;
case 'l':
System.out.println("当前队列的元素个数为:"+arrayQueue.queueSize());
break;
default:
System.out.println("尚未支持的操作");
}
System.out.println();
}
System.out.println("程序退出");
}
}
class CircularQueue {
private int maxSize ; //表示数组的最大容量
private int front; //指向队列的第一个元素位置,初始值为0
private int rear; //队列最后一个元素的下一个位置,初始值为0
private int[] arr; //用于存放数据的数组
//创建队列的构造器
public CircularQueue(int arrMaxSize) {
maxSize = arrMaxSize;
arr = new int[maxSize];
front = 0; //指向队列前面一个位置
rear = 0; //指向队列尾的位置,队列最后一个元素+1
}
//判断队列是否满
public boolean isFull() {
return (rear + 1 + maxSize) % maxSize == front;
}
//判断队列是否为空
public boolean isEmpty() {
return rear == front;
}
//添加数据到队列
public void addQueue(int e) {
if ( !isFull() ) {
arr[rear] = e;
rear = ++rear % maxSize;
} else {
System.out.printf("queue is full add failed");
return;
}
}
//获取数据
public int pop() {
if (isEmpty()) {
//抛出异常
throw new RuntimeException("队列空,不能取出数据");
}
int e = arr[front];
front = ++front % maxSize;
return e;
}
//显示队列的所有数据
public void showQueue() {
if (isEmpty()) {
System.out.printf("队列为空,没有数据。");
return;
}
int cnt = queueSize();
int index = 0;
for (int i = front; i < front+cnt; i++) {
index = i % maxSize;
System.out.printf("%d\t", arr[index]);
}
System.out.println();
}
//显示队列的头
public int peakQueue() {
if (isEmpty()) {
throw new RuntimeException("队列没有数据");
}
return arr[front];
}
//查询当前队列一共有多少个元素
public int queueSize() {
return (rear + maxSize - front) % maxSize;
}
}