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 }