數組模擬隊列
/** * 使用數組模擬隊列 * @author Administrator */ public class ArrayQueueDemo { public static void main(String[] args) { ArrayQueue arrayQueue = new ArrayQueue(3); arrayQueue.addQueue(2); arrayQueue.addQueue(4); arrayQueue.addQueue(6); arrayQueue.showQueue(); } } //使用數組模擬一個有序隊列 class ArrayQueue{ private int front = -1;//隊列頭 private int rear = -1;//隊列尾 private int maxSize;//表示數組的最大容量 private int[] arr ;//該數組用於存放數據,模擬隊列 //構造函數初始化隊列 public ArrayQueue(int maxSize){ this.maxSize = maxSize; arr = new int[maxSize]; } //判斷是否滿了 public boolean fullQueue(){ return rear == maxSize-1; } //判斷是否為空 public boolean isEmpty(){ return rear == front; } //添加元素 public void addQueue(int n){ //校驗是否滿了 if (fullQueue()) { System.out.println("隊列已經滿了"); return; } //添加到隊列中 rear++; arr[rear] = n; } //去除元素 public int removeQueue(){ //校驗是否為空 if (isEmpty()) { throw new RuntimeException("當前為空不能去除元素!"); } front++; return arr[front]; } public void showQueue(){ if (!isEmpty()) { for (int i = 0; i < arr.length; i++) { System.err.println(arr[i]); } } } }