02java算法与数据结构------队列用数组代码实现




 1 import java.util.Scanner;
 2 
 3 public class Test {
 4     static int rear;
 5     static int front;
 6     static int maxSize;
 7 
 8     public static void main(String[] args) {
 9         //队列用数组来实现
10         Scanner sc = new Scanner(System.in);
11         System.out.println("请你输入队列的最大值");
12         maxSize = sc.nextInt();
13         int[] arr = new int[maxSize];
14         //队列的尾;
15         rear = -1;
16         //队列的头;
17         front = -1;
18         //队列用数组来实现 ---给数组添加值
19         while (true) {
20             System.out.println("请你添加数组的值");
21             int count = sc.nextInt();
22             rear++;
23             arr[rear] = count;
24             if (getfull()) {
25                 System.out.println("请你添加数组的值已经满了");
26                 break;
27             }
28         }
29         //队列用数组来实现 ---给数组添加值-----遍历
30         for (int i = 0; i < arr.length; i++) {
31             if (getempty()) {
32                 System.out.println("该数组为空");
33                 break;
34             }
35             System.out.println(arr[i]);
36         }
37     }
38 
39     public static boolean getfull() {
40         return rear == maxSize - 1;
41     }
42 
43     public static boolean getempty() {
44         return rear == front;
45     }
46 }