隊列是一個有序列表,能夠用數組或者鏈表來實現java
遵循先進先出的原則。即:先存入隊列的數據,要先取出。後存入的要後取出數組
package io.gjf.T02_Queen; import java.util.Scanner; /** * Create by GuoJF on 2019/12/17 */ public class App_ArrayQueen { public static void main(String[] args) { ArrayQueen arrayQueen = new ArrayQueen(4); // 接收用戶輸入 char c = ' '; Scanner scanner = new Scanner(System.in); boolean loap = true; while (loap) { System.out.println("s(show) : 顯示隊列"); System.out.println("g(get) : 獲取隊列數據"); System.out.println("e(exit) : 退出程序"); System.out.println("h(head) : 顯示頭部數據"); System.out.println("a(add) : 添加數據"); c = scanner.next().charAt(0); switch (c) { case 's': try { arrayQueen.showData(); } catch (Exception e) { System.out.println(e.getMessage()); } break; case 'g': try { int data = arrayQueen.getData(); System.out.println("獲取到當前的數據爲" + data); } catch (Exception e) { System.out.println(e.getMessage()); } break; case 'a': int n = scanner.nextInt(); try { arrayQueen.addData(n); } catch (Exception e) { System.out.println(e.getMessage()); } break; case 'h': try { int data = arrayQueen.showFront(); System.out.println("獲取到當前的數據爲" + data); } catch (Exception e) { System.out.println(e.getMessage()); } break; case 'e': loap = false; break; default: System.out.println("請輸入正確的代碼"); break; } System.out.println("程序正在退出...."); } } } class ArrayQueen { private int maxSize; private int rear; //表明數組尾部下標 private int front; //表明數組頭部下標 private int[] array; // 模擬隊列的數組 /* * 使用構造方法建立數組 * */ public ArrayQueen(int size) { maxSize = size; array = new int[maxSize]; front = 0; rear = 0; } public void addData(int n) { if (isFull()) { throw new RuntimeException("隊列已滿,沒法添加!"); } array[rear] = n; // rear++; 不能++ 由於要模擬環形隊列 rear = (rear + 1) % maxSize; } public int getData() { if (idEmpty()) { throw new RuntimeException("隊列爲空,沒法獲取!"); } // 獲得當前隊列中最靠前的一個元素 int value = array[front]; // 將front 後移 front = (front + 1) % maxSize; return value; } public void showData() { if (idEmpty()) { throw new RuntimeException("隊列爲空,沒法獲取!"); } for (int i = front; i < front + getSum(); i++) { System.out.printf("array[%d]=%d\n", i % maxSize, array[i % maxSize]); } } public int getSum() { return (rear + maxSize - front) % maxSize; } public int showFront() { if (idEmpty()) { throw new RuntimeException("隊列爲空,沒法獲取!"); } return array[front]; } public boolean idEmpty() { return rear == front; } public boolean isFull() { return (rear + 1) % maxSize == front; } }