1 package com.java.test;
2
3 import java.util.Scanner;
4
5 public class D1 {
6 public static void main(String[] args) {
7 System.out.println("测试数组模拟环形队列的案例~~~");
8 // 创建一个环形队列
9 CircleArrayQueue queue = new CircleArrayQueue(4); //说明设置 4, 其队列的有效数据最大是 3
10 char key = ' '; // 接收用户输入
11 Scanner scanner = new Scanner(System.in);//
12 boolean loop = true;
13 // 输出一个菜单
14 while (loop) {
15 System.out.println("s(show): 显示队列");
16 System.out.println("e(exit): 退出程序");
17 System.out.println("a(add): 添加数据到队列");
18 System.out.println("g(get): 从队列取出数据");
19 System.out.println("h(head): 查看队列头的数据");
20 key = scanner.next().charAt(0);// 接收一个字符
21 switch (key) {
22 case 's':
23 queue.showQueue();
24 break;
25 case 'a':
26 System.out.println("输出一个数");
27 int value = scanner.nextInt();
28 queue.addQueue(value);
29 break;
30 case 'g': // 取出数据
31 try {
32 int res = queue.getQueue();
33 System.out.printf("取出的数据是%d\n", res);
34 } catch (Exception e) {
35 // TODO: handle exception
36 System.out.println(e.getMessage());
37 }
38 break;
39 case 'h': // 查看队列头的数据
40 try {
41 int res = queue.headQueue();
42 System.out.printf("队列头的数据是%d\n", res);
43 } catch (Exception e) {
44 // TODO: handle exception
45 System.out.println(e.getMessage());
46 }
47 break;
48 case 'e': // 退出
49 scanner.close();
50 loop = false;
51 break;
52 default:
53 break;
54 }
55 }
56 System.out.println("程序退出~~");
57 }
58 }
59
60 //数组模拟环形队列
61 class CircleArrayQueue {
62 private int maxSize; //队列的最大长度,队列的有效长度为maxSize-1,空出一个空间
63 private int front; //队列头下标,指向队列的第一个数据,初始值为0
64 private int rear; //队列的尾下标,指向队列最后一个数据的后面一位,初始值为0
65 private int arr[]; //存放数据,模拟队列
66
67 //初始化队列
68 public CircleArrayQueue(int arrMaxSize) {
69 this.maxSize = arrMaxSize;
70 arr = new int[maxSize];
71 front = 0; // 指向队列头部
72 rear = 0; // 指向队列尾的后一个位置
73 }
74
75 public boolean isFull() {
76 return (rear + 1) % maxSize == front;
77 }
78
79 public boolean isEmpty() {
80 return front == rear;
81 }
82
83 //出队列
84 public int getQueue() {
85 if (isEmpty()) {
86 throw new RuntimeException("队列空,无法出队列");
87 } else {
88 int value = arr[front];
89 //因为是环形队列,当取出尾部(maxsize-1下标)的数字时,取模回到0下标
90 front = (front + 1) % maxSize;
91 return value;
92 }
93 }
94
95 //进队列
96 public void addQueue(int num) {
97 if (isFull()) {
98 System.out.println("队列满,无法进队列");
99 } else {
100 arr[rear] = num;
101 rear = (rear + 1) % maxSize;
102 }
103 }
104
105 public void showQueue() {
106 if (isEmpty()) {
107 throw new RuntimeException("队列空,无数据");
108 } else {
109 for (int i = front; i < front + ((rear - front + maxSize) % maxSize); i++) {
110 System.out.printf("arr[%d]=%d\n", i % maxSize, arr[i % maxSize]);
111 }
112 }
113 }
114
115 // 显示队列的头数据
116 public int headQueue() {
117 if (isEmpty()) {
118 throw new RuntimeException("队列空的,没有数据~~");
119 }
120 return arr[front];
121 }
122 }