一.隊列介紹
1.隊列是一個有序列表,可以用數組或是鏈表來實現。
2.遵循先入先出的原則。即:先存入隊列的數據,要先取出。後存入的要後取出
3.示意圖:(使用數組模擬隊列示意圖)
二.數組模擬隊列思路:
1.隊列本身是有序列表,若使用數組的結構來存儲隊列的數據,則隊列數組的聲明如下圖,其中maxSize是該隊列的最大容量。
2.因爲隊列的輸出、輸入是分別從前後端來處理,因此需要兩個變量front及rear分別記錄隊列前後端的下標,front會隨着數據輸出而改變,而rear則是隨着數據輸入而改變。
3.當我們將數據存入隊列時稱爲”addQueue”,addQueue的處理需要有兩個步驟:
思路分析
(1)將尾指針往後移:rear+1,當(front等於rear)時隊列爲空。
(2)若尾指針rear小於隊列的最大下標maxSize-1,則將數據存入rear所指的數組元素中,否則無法存入數據。rear=maxSize-1時隊列滿。
三.代碼實現
package com.atguigu.queue;
import java.util.Scanner;
public class ArrayQueueDemo {
public static void main(String[] args) {
//測試一把
//創建一個隊列
ArrayQueue queue = new ArrayQueue(3);
char key = ' '; //接收用戶輸入
Scanner scanner = new Scanner(System.in);//
boolean loop = true;
//輸出一個菜單
while(loop) {
System.out.println("s(show): 顯示隊列");
System.out.println("e(exit): 退出程序");
System.out.println("a(add): 添加數據到隊列");
System.out.println("g(get): 從隊列取出數據");
System.out.println("h(head): 查看隊列頭的數據");
key = scanner.next().charAt(0);//接收一個字符
switch (key) {
case 's':
queue.showQueue();
break;
case 'a':
System.out.println("輸出一個數");
int value = scanner.nextInt();
queue.addQueue(value);
break;
case 'g': //取出數據
try {
int res = queue.getQueue();
System.out.printf("取出的數據是%d\n", res);
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
}
break;
case 'h': //查看隊列頭的數據
try {
int res = queue.headQueue();
System.out.printf("隊列頭的數據是%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("程序退出~~");
}
}
// 使用數組模擬隊列-編寫一個ArrayQueue類
class ArrayQueue {
private int maxSize; // 表示數組的最大容量
private int front; // 隊列頭
private int rear; // 隊列尾
private int[] arr; // 該數據用於存放數據, 模擬隊列
// 創建隊列的構造器
public ArrayQueue(int arrMaxSize) {
maxSize = arrMaxSize;
arr = new int[maxSize];
front = -1; // 指向隊列頭部,分析出front是指向隊列頭的前一個位置.
rear = -1; // 指向隊列尾,指向隊列尾的數據(即就是隊列最後一個數據)
}
// 判斷隊列是否滿
public boolean isFull() {
return rear == maxSize - 1;
}
// 判斷隊列是否爲空
public boolean isEmpty() {
return rear == front;
}
// 添加數據到隊列
public void addQueue(int n) {
// 判斷隊列是否滿
if (isFull()) {
System.out.println("隊列滿,不能加入數據~");
return;
}
rear++; // 讓rear 後移
arr[rear] = n;
}
// 獲取隊列的數據, 出隊列
public int getQueue() {
// 判斷隊列是否空
if (isEmpty()) {
// 通過拋出異常
throw new RuntimeException("隊列空,不能取數據");
}
front++; // front後移
return arr[front];
}
// 顯示隊列的所有數據
public void showQueue() {
// 遍歷
if (isEmpty()) {
System.out.println("隊列空的,沒有數據~~");
return;
}
for (int i = 0; i < arr.length; i++) {
System.out.printf("arr[%d]=%d\n", i, arr[i]);
}
}
// 顯示隊列的頭數據, 注意不是取出數據
public int headQueue() {
// 判斷
if (isEmpty()) {
throw new RuntimeException("隊列空的,沒有數據~~");
}
return arr[front + 1];
}
}
注意:
此模擬方法數組只能用一次,優化見博文-java數據結構-數組模擬環形隊列。