package Learning;
import java.util.Scanner;
/**
* @author Yan_Bingo
* @version 1.0
* Create by 2023/9/23 11:01
*/
public class CircleArrayQueueDemo {
public static void main(String[] args) {
CircleArrayQueue queue = new CircleArrayQueue(5); //设置为5, 环形队列有效数据最大量为 4
boolean loop = true;
char key = ' '; // 接收用户的输入
Scanner scanner = new Scanner(System.in);
while (loop) {
System.out.println();
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): 显示队列头");
key = scanner.next().charAt(0); // 接收用户输入的第一个字符
switch (key) {
case 's':
try {
queue.showQueue();
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'e':
System.out.println("程序即将退出,再见~~");
loop = false;
break;
case 'a':
try {
System.out.print("请输入要添加的数据:");
int value = scanner.nextInt();
queue.addQueue(value);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'g':
try {
int value = queue.getQueue();
System.out.println(value);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'h':
try {
queue.showHead();
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
default:
break;
}
}
}
}
class CircleArrayQueue{
private int maxSize;
private int front; // 指向队列的第二个元素
private int rear; // 指向队列最后一个元素的下一位
private int [] array;
/* 创建环形队列的构造器 */
public CircleArrayQueue(int arrSize){
maxSize = arrSize;
array = new int[maxSize];
}
/* 判断环形队列是否为空 */
public boolean isEmpty(){
return front == rear;
}
/* 判断环形队列是否已满 */
public boolean isFull(){
return (rear + 1) % maxSize == front ;
}
// 展示环形队列的首个数据
public void showHead(){
if (isEmpty()){
throw new RuntimeException("当前队列为空!!!没有数据~~");
}
System.out.println("当前队列首个元素为: " + array[front]);
}
// 取出环形队列数据
public int getQueue(){
// 判断队列是否为空
if(isEmpty()){
throw new RuntimeException("当前队列为空!!!,没有数据~");
}
int value = array[front];
front = (front + 1) % maxSize;
return value;
}
// 向环形队列添加数据
public void addQueue(int value){
// 判断队列是否已满
if(isFull()){
throw new RuntimeException("当前队列已满,无法添加数据");
}
array[rear] = value;
rear = (rear + 1) % maxSize;
}
// 获取队列有效数据的个数
public int size(){
return (rear + maxSize - front) % maxSize;
}
// 展示队列
public void showQueue(){
if(isEmpty()){
throw new RuntimeException("当前队列为空,没有数据~~");
}
for (int i = front; i < front + size() ; i++) {
System.out.printf("arr[%d] = %d\n", i % maxSize, array[i % maxSize]);
}
}
}
Java 数组模拟环形队列
最新推荐文章于 2024-11-01 14:48:20 发布