數組實現環形隊列


1. 簡介

隊列是一個有序列表,可以用數組或是鏈表來實現。
遵循先入先出的原則。即:先存入隊列的數據,要先取出。后存入的要后取出
示意圖:(使用數組模擬隊列示意圖)

2. 數組模擬隊列

實現思路

隊列本身是有序列表,若使用數組的結構來存儲隊列的數據,則隊列數組的聲明如下圖, 其中 maxSize 是該隊列的最大容量。
因為隊列的輸出、輸入是分別從前后端來處理,因此需要兩個變量 front rear分別記錄隊列前后端的下標,front 會隨着數據輸出而改變,而 rear則是隨着數據輸入而改變,如圖所示:

當我們將數據存入隊列時稱為addQueueaddQueue 的處理需要有兩個步驟:思路分析
將尾指針往后移:rear+1 , 當front == rear【空】
若尾指針 rear 小於隊列的最大下標 maxSize-1,則將數據存入 rear所指的數組元素中,否則無法存入數據。 rear == maxSize - 1[隊列滿]

具體代碼如下

隊列代碼

package com.queue;

/**
 * 使用數組模擬隊列
 *
 * @author john
 * @date 2019/12/17 - 17:49
 */
class ArrayQueue {
    private int maxSize; //數組的最大容量
    private int front; //隊列頭
    private int rear;  //隊列尾
    private int[] arr; //該數組用於存放數據,模擬隊列

    //創建隊列的構造器
    public ArrayQueue(int maxSize) {
        this.maxSize = maxSize;
        arr = new int[this.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];
    }
}

測試代碼

package com.queue;


import java.util.Scanner;

/**
 * @author john
 * @date 2019/12/17 - 17:48
 */
public class ArrayQueueDemo {
    public static void main(String[] args) {
        //  數組模擬隊列
        ArrayQueue queue = new ArrayQueue(3);
        doLoop(queue);
    }

    //用於測試隊列
    public static void doLoop(ArrayQueue queue) {
        char key; // 用於接收用戶輸入
        int res; //用於取出隊列中的數據
        Scanner sc = new Scanner(System.in);
        boolean loop = true;    //判斷是否需要繼續執行

        // 提示信息
        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): 查看隊列頭的數據");

        while (loop) {
            key = sc.next().charAt(0); //接收一個字符
            switch (key) {
                case 's':
                    queue.showQueue();
                    break;
                case 'a':
                    System.out.println("請輸入一個數用於插入隊列");
                    int varlue = sc.nextInt();
                    queue.addQueue(varlue);
                    break;
                case 'g':
                    try {
                        res = queue.getQueue();
                        System.out.printf("從隊列取出的數據是%d\n", res);
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'h':
                    res = queue.headQueue();
                    System.out.printf("隊列頭的數據是%d\n", res);
                    break;
                case 'e':
                    sc.close();
                    loop = false;
                    break;
                default:
                    break;
            }
            System.out.println("程序運行結束");
        }
    }

}

運行結果

問題分析並優化

  1. 目前數組使用一次就不能用,沒有達到復用的效果

  2. 將這個數組使用算法,改進為一個環形的隊列

3. 數組模擬環形隊列

對前面的數組模擬隊列的優化,充分利用數組,因此將數組看做是一個環形的(通過取模實現)

思路分析

  1. front 變量的含義做一個調整: front 就指向隊列的第一個元素, 也就是說 arr[front] 就是隊列的第一個元素
    front 的初始值 = 0
  2. rear 變量的含義做一個調整:rear 指向隊列的最后一個元素的后一個位置. 因為希望空出一個空間做為約定.
    rear 的初始值 = 0
  3. 當隊列滿時,條件是 (rear + 1) % maxSize == front 【滿】
  4. 對隊列為空的條件, rear == front
  5. 當我們這樣分析, 隊列中有效的數據的個數 (rear + maxSize - front) % maxSize // rear = 1 front = 0
  6. 我們就可以在原來的隊列上修改得到,一個環形隊列

代碼實現

隊列代碼

package com.queue;

/**
 * 環形隊列
 * @author john
 * @date 2019/12/17 - 18:41
 */
class CircleArrayQueue {
    private int maxSize; //數組的最大容量
    private int front; //front指向隊列的第一個元素,初始值為0
    private int rear;  //rear指向隊列的最后一個元素的后一個位置,因此希望空出一個空間作為約定,初始值為0
    private int[] arr; //該數組用於存放數據,模擬隊列

    //創建隊列的構造器
    public CircleArrayQueue(int maxSize) {
        this.maxSize = maxSize;
        arr = new int[this.maxSize];
    }

    // 判斷隊列是否已滿
    public boolean isFull() {
        return (rear + 1) % maxSize == front;
    }

    //判斷隊列是否為空
    public boolean isEmpty() {
        return rear == front;
    }

    //添加數據到隊列
    public void addQueue(int n) {
        //判斷隊列是否已滿
        if (isFull()) {
            System.out.println("隊列已滿,不能加入數據了");
            return;
        }
        //直接將數據加入
        arr[rear] = n;
        //將rear后移,這里需要取模
        rear = (rear + 1) % maxSize;
    }

    // 獲取隊列的數據,出隊列
    public int getQueue() {
        //判斷隊列是否為空
        if (isEmpty()) {
            //跑出異常
            throw new RuntimeException("隊列空,不能取數據");
        }
        // 1. 先把front值保存到一個臨時變量
        int value = arr[front];
        // 2. 將front后移,考慮取模
        front = (front + 1) % maxSize;
        // 3. 將臨時保存的變量返回
        return value;
    }

    //顯示隊列的所有數據
    public void showQueue() {
        //為空判斷
        if (isEmpty()) {
            System.out.println("隊列空的,沒有數據");
            return;
        }
        //遍歷
        for (int i = front; i < front + size(); i++) {
            System.out.printf("arr[%d]=%d\n", i % maxSize, arr[i % maxSize]);
        }
    }

    //顯示隊列的頭數據,不取出數據
    public int headQueue() {
        //為空判斷
        if (isEmpty()) {
            throw new RuntimeException("隊列空,不能取數據");
        }
        return arr[front];
    }

    //求出當前隊列有效數據的個數
    public int size() {
        return (rear + maxSize - front) % maxSize;
    }
}

測試代碼

package com.queue;


import java.util.Scanner;

/**
 * @author john
 * @date 2019/12/17 - 17:48
 */
class ArrayQueueDemo {
    public static void main(String[] args) {
        //測試數組環形隊列
        CircleArrayQueue queue = new CircleArrayQueue(4); //實際隊列長度最大只有3
        doLoop(queue);
    }

    //用於測試隊列
    public static void doLoop(CircleArrayQueue queue) {
        char key; // 用於接收用戶輸入
        int res; //用於取出隊列中的數據
        Scanner sc = new Scanner(System.in);
        boolean loop = true;    //判斷是否需要繼續執行

        // 提示信息
        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): 查看隊列頭的數據");

        while (loop) {
            key = sc.next().charAt(0); //接收一個字符
            switch (key) {
                case 's':
                    queue.showQueue();
                    break;
                case 'a':
                    System.out.println("請輸入一個數用於插入隊列");
                    int varlue = sc.nextInt();
                    queue.addQueue(varlue);
                    break;
                case 'g':
                    try {
                        res = queue.getQueue();
                        System.out.printf("從隊列取出的數據是%d\n", res);
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'h':
                    res = queue.headQueue();
                    System.out.printf("隊列頭的數據是%d\n", res);
                    break;
                case 'e':
                    sc.close();
                    loop = false;
                    break;
                default:
                    break;
            }
        }
        System.out.println("程序運行結束");
    }

}

測試結果



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM