1. 程式人生 > >java資料結構——環形佇列

java資料結構——環形佇列

ArrayQueue存在一個問題,假設當尾部插入元素滿了,頭部又刪掉了一些元素,這種情況下,就誤認為空間滿了,造成了假溢位,實際上頭部刪除了元素留出了空間。這時候環形佇列就解決了這樣的一個問題,環形佇列的front指標始終指向當前佇列的最後位置;end指標始終指向第一個元素的前一個位置為-1,儲存元素的時候頭部和尾部都可以相互移動,而不必造成假溢位現象,節省了記憶體空間。如下:

1、構造方法

class CircleQueue {

    //隊頭
    private int front;
    //隊尾
    private int end;
    //佇列有效長度
    private int elements;
    //佇列
    private long[] queue;

    public CircleQueue() {
        queue = new long[5];
        front = -1;
        end = -1;
    }

    public CircleQueue(int length) {
        queue = new long[length];
        front = -1;
        end = -1;
    }
}

2、新增佇列

    /**
     * 插入元素
     */
    public void add(int value) {
        if (isFull()) {
            System.out.println("佇列已滿,請刪除");
            throw new IndexOutOfBoundsException();
        }
        if (isEmpty()) {
            front = 0;
        }
        if ((end == queue.length - 1)) {
            end = -1;
        }
        queue[++end] = value;
        elements++;
    }

3、刪除佇列

    /**
     * 刪除元素
     */
    public void delete() {
        if ((front == queue.length)) {
            front = -1;
        }
        queue[front] = -1;
        front++;
        elements--;
    }

4、檢視佇列元素

    /**
     * 檢視佇列
     */
    public void display() {
        if (isEmpty()) {
            System.out.println("元素為空,請先插入元素");
        }
        for (int i = 0; i < queue.length; i++) {
            if (queue[i] == -1) {
                //X為佔位符,表示該節點元素沒有元素
                System.out.print("X" + " ");
            } else {
                System.out.print(queue[i] + " ");
            }
        }
        System.out.println();
    }

5、檢視隊頭

    /**
     * 檢視隊頭
     */
    public long getFront() {
        if (isEmpty()) {
            System.out.println("隊尾為空");
            return 0;
        }
        return queue[front];
    }

6、檢視隊尾

    /**
     * 檢視隊尾
     */
    public long getEnd() {
        if (isEmpty()) {
            return -1;
        }
        return queue[end];
    }

7、檢視佇列元素個數

    /**
     * 檢視佇列裡面幾個元素
     */
    public int size() {
        return elements;
    }

8、佇列是否為空

    /**
     * 佇列是否為空
     */
    public boolean isEmpty() {
        return elements == 0;
    }

9、佇列是否滿了

    /**
     * 佇列是否滿了
     */
    public boolean isFull() {
        return elements == queue.length;
    }

下一篇將介紹優先佇列。