使用陣列模擬佇列,先進先出的特性,並且陣列可覆用儲存新的值。
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
CircularQueue queue = new CircularQueue(3);
Scanner scanner = new Scanner(System.in);
char choice = ' ';
boolean loop = true;
while (loop) {
System.out.println("選擇(s)_show,顯示佇列");
System.out.println("選擇(a)_add,新增佇列");
System.out.println("選擇(g)_get,取出佇列的值");
System.out.println("選擇(h)_head,顯示佇列頭的值");
System.out.println("選擇(e)_exit,退出程式");
choice = scanner.next().charAt(0);
switch (choice) {
case 's' :
try {
queue.showQueue();
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'a' :
System.out.println("請輸入一個數");
int value = scanner.nextInt();
try {
queue.addQueue(value);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'g' :
try {
int res = queue.getQueue();
System.out.printf("取出的資料為%d\n", res);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'h' :
try {
int headQueue = queue.getHeadQueue();
System.out.printf("headQueue = %d\n", headQueue);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'e' :
scanner.close();
loop = false;
break;
default :
break;
}
}
}
}
/**
* 陣列模擬環形佇列
*/
class CircularQueue {
// declare fields
private int length; // queue length
private int front; // an index of before head queue
private int rear; // the end of queue
private int[] arr; // to store values
// declare a constructor, aim to new an array
CircularQueue(int length) {
this.length = length;
this.arr = new int[length];
// this.front = 0;
// this.rear = 0;
}
private boolean isFull() {
return length == getCircularQueueNum();
}
private boolean isEmpty() {
return front == rear;
}
// declare a function for addQueue
public void addQueue(int value) {
if(isFull()) {
throw new ArrayIndexOutOfBoundsException("佇列已滿,不能新增資料");
}
// add data
arr[rear % length] = value;
rear++;
}
public int getQueue() {
if (isEmpty()) {
throw new RuntimeException("佇列無資料~~");
}
// get data
int temp = arr[front % length];
front++;
return temp;
}
public int getHeadQueue() {
if (isEmpty()) {
throw new RuntimeException("佇列無資料~~");
}
return arr[front % length];
}
public void showQueue() {
if (isEmpty()) {
throw new RuntimeException("佇列無資料~~");
}
for (int i = front; i < front + getCircularQueueNum(); i++) {
System.out.printf("arr[%d] = %d\n", i % length, arr[i % length]);
}
}
public int getCircularQueueNum() {
int n; // current number of value in CircularQueue
if (rear < front) {
n = rear + length - front;
} else {
n = rear - front;
}
return n;
}
}
如有敘述錯誤,還請不吝嗇留言指教,thanks!