package com.atguigu.queue;
import java.util.Scanner;
public class ArrayQueueDemo {
public static void main(String[] args) {
//測(cè)試一把
//創(chuàng)建一個(gè)隊(duì)列
ArrayQueue queue = new ArrayQueue(3);
char key = ' '; //接收用戶輸入
Scanner scanner = new Scanner(System.in);//
boolean loop = true;
//輸出一個(gè)菜單
while(loop) {
System.out.println("s(show): 顯示隊(duì)列");
System.out.println("e(exit): 退出程序");
System.out.println("a(add): 添加數(shù)據(jù)到隊(duì)列");
System.out.println("g(get): 從隊(duì)列取出數(shù)據(jù)");
System.out.println("h(head): 查看隊(duì)列頭的數(shù)據(jù)");
key = scanner.next().charAt(0);//接收一個(gè)字符
switch (key) {
case 's':
queue.showQueue();
break;
case 'a':
System.out.println("輸出一個(gè)數(shù)");
int value = scanner.nextInt();
queue.addQueue(value);
break;
case 'g': //取出數(shù)據(jù)
try {
int res = queue.getQueue();
System.out.printf("取出的數(shù)據(jù)是%d\n", res);
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
}
break;
case 'h': //查看隊(duì)列頭的數(shù)據(jù)
try {
int res = queue.headQueue();
System.out.printf("隊(duì)列頭的數(shù)據(jù)是%d\n", res);
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
}
break;
case 'e': //退出
scanner.close();
loop = false;
break;
default:
break;
}
}
System.out.println("程序退出~~");
}
}
// 使用數(shù)組模擬隊(duì)列-編寫一個(gè)ArrayQueue類
class ArrayQueue {
private int maxSize; // 表示數(shù)組的最大容量
private int front; // 隊(duì)列頭
private int rear; // 隊(duì)列尾
private int[] arr; // 該數(shù)據(jù)用于存放數(shù)據(jù), 模擬隊(duì)列
// 創(chuàng)建隊(duì)列的構(gòu)造器
public ArrayQueue(int arrMaxSize) {
maxSize = arrMaxSize;
arr = new int[maxSize];
front = -1; // 指向隊(duì)列頭部,分析出front是指向隊(duì)列頭的前一個(gè)位置.
rear = -1; // 指向隊(duì)列尾,指向隊(duì)列尾的數(shù)據(jù)(即就是隊(duì)列最后一個(gè)數(shù)據(jù))
}
// 判斷隊(duì)列是否滿
public boolean isFull() {
return rear == maxSize - 1;
}
// 判斷隊(duì)列是否為空
public boolean isEmpty() {
return rear == front;
}
// 添加數(shù)據(jù)到隊(duì)列
public void addQueue(int n) {
// 判斷隊(duì)列是否滿
if (isFull()) {
System.out.println("隊(duì)列滿,不能加入數(shù)據(jù)~");
return;
}
rear++; // 讓rear 后移
arr[rear] = n;
}
// 獲取隊(duì)列的數(shù)據(jù), 出隊(duì)列
public int getQueue() {
// 判斷隊(duì)列是否空
if (isEmpty()) {
// 通過拋出異常
throw new RuntimeException("隊(duì)列空,不能取數(shù)據(jù)");
}
front++; // front后移
return arr[front];
}
// 顯示隊(duì)列的所有數(shù)據(jù)
public void showQueue() {
// 遍歷
if (isEmpty()) {
System.out.println("隊(duì)列空的,沒有數(shù)據(jù)~~");
return;
}
for (int i = 0; i < arr.length; i++) {
System.out.printf("arr[%d]=%d\n", i, arr[i]);
}
}
// 顯示隊(duì)列的頭數(shù)據(jù), 注意不是取出數(shù)據(jù)
public int headQueue() {
// 判斷
if (isEmpty()) {
throw new RuntimeException("隊(duì)列空的,沒有數(shù)據(jù)~~");
}
return arr[front + 1];
}
}