1 public class Queue {
2 //队首指针
3 private int front;
4 //队尾指针
5 private int rear;
6 //数组
7 private int[] arr;
8 //数组最大长度
9 private int maxSize;
10
11 //初始化队列长度
12 public Queue(int maxSize){
13 this.maxSize = maxSize;
14 arr = new int[maxSize];
15 }
16
17 //是否为空
18 public boolean isEmpty(){
19 if (front == rear){
20 return true;
21 }
22 else
23 return false;
24 }
25
26 //是否为满队列
27 public boolean isFull(){
28 if(front == (rear+1)%maxSize){
29 return true;
30 }
31 else
32 return false;
33 }
34
35 //计算当前元素个数
36 public int queueSize(){
37 return (rear + maxSize - front) % maxSize;
38 }
39
40 //进队
41 public void enQueue(int x){
42 //判断是否为满队列
43 if(isFull()){
44 throw new RuntimeException("队列已满,无法插入新元素");
45 }
46 arr[rear] = x;
47 rear = (rear+1)%maxSize;
48 }
49
50 //出队
51 public int deQueue(){
52 if(isEmpty()){
53 throw new RuntimeException("队列为空,无法出队元素");
54 }
55 int value = arr[front];
56 front = (front + 1)%maxSize;
57 return value;
58 }
59
60 //显示队列里的数据
61 public void showQueue(){
62 if(isEmpty()){
63 System.out.println("队列为空");
64 return;
65 }
66 for (int i = front; i < front + queueSize() ; i++){
67 System.out.println("arr[" + i + "] = " + arr[i]);
68 }
69 return;
70 }
71 }