02、手寫佇列
阿新 • • 發佈:2021-02-15
技術標籤:資料結構
佇列的特性是:先進先出;
package com.vicbaily.queue; public class ArrayQueueDemo { public static void main(String[] args) { int maxSize = 3 ; ArrayQueue queue = new ArrayQueue(maxSize); for (int index = 0; index < maxSize; index++) { double value = Math.random(); System.out.print(value + "\t"); queue.addQueue(value); } System.out.println(); System.out.println("=================================="); for (int index = 0; index < maxSize; index++) { System.out.print(queue.getQueue() + "\t"); } } } class ArrayQueue { private int maxSize; // 最大容量 private int front; // 字首指標 private int rear; // 字尾指標 private double[] arr; // 佇列容量 // 佇列構造器,建立容量 public ArrayQueue(int maxSize) { this.maxSize = maxSize; arr = new double[maxSize]; front = -1; rear = -1; } public boolean isFull(){ return maxSize == rear + 1; } public boolean isEmpty() { return rear == front; } public void addQueue(double n) { if (isFull()) { System.out.println("佇列已經滿了"); return; } rear++; arr[rear] = n; } public double getQueue() { if (isEmpty()) { throw new RuntimeException("佇列為空"); } front++; return arr[front]; } public void showQueue() { if (isEmpty()) { System.out.println("佇列為空"); return; } for (int index = 0; index < arr.length; index++) { System.out.printf("%d\t", arr[index]); } } public double headQueue() { if (isEmpty()) { throw new RuntimeException("佇列為空"); } return arr[front + 1]; } }
執行結果為:
0.5237874587129546 0.5958271076564382 0.9547179942382022
==================================
0.5237874587129546 0.5958271076564382 0.9547179942382022