Java 隊列 (Queue)

這是這段時間學習隊列的筆記和總結。

概述

隊列是一種先進先出的數據結構(FIFO),就是第一個元素進去,第一個現出來。

queue的主要操作

boolean add(E var1); // 增加一個元索 如果隊列已滿,則拋出一個IIIegaISlabEepeplian
異常(拋出異常,不建議使用)
boolean offer(E var1); // 添加一個元素並返回true 如果隊列已滿,則返回false
E remove(); // 移除並返回隊列頭部的元素 如果隊列爲空,則拋出一個NoSuchElementException異常(拋出異常,不建議使用)
E poll(); // 移除並返問隊列頭部的元素 如果隊列爲空,則返回null
E element(); // 返回隊列頭部的元素 如果隊列爲空,則拋出一個NoSuchElementException異常(拋出異常,不建議使用)
E peek(); // 返回隊列頭部的元素 如果隊列爲空,則返回null

一個Queue使用的列子:

private static void testQueue() {
    //add()和remove()方法在失敗的時候會拋出異常(不推薦)
    Queue<String> queue = new LinkedList<>();
    //添加元素
    queue.offer("a");
    queue.offer("b");
    queue.offer("c");
    queue.offer("d");
    queue.offer(null);
    for(String q : queue){
        System.out.println(q);
    }
    System.out.println("====================");
    String p = queue.poll();
    System.out.println(p);
    for(String q : queue){
        System.out.println(q);
    }
    System.out.println("====================");
    String pe = queue.peek();
    System.out.println(pe);
    for(String q : queue){
        System.out.println(q);
    }
}

注意問題:
上面使用的LinkedList可以添加null元素,但一般不建議,因爲當隊列爲空的時候,使用poll()方法返回null,這個時候無法區分是沒有元素,還是添加的null元素,所以不建議添加null元素。

數組隊列

這是一個使用數組封裝實現的隊列:
Queue.java:

public interface Queue<E> {
    int getSize();
    boolean isEmpty();
    void enqueue(E e);
    E dequeue();
    E getFront();
}

ArrayQueue.java:

public class ArrayQueue<E> implements Queue<E> {

    private Array<E> array;

    public ArrayQueue(int capacity){
        array = new Array<>(capacity);
    }

    public ArrayQueue(){
        array = new Array<>();
    }

    @Override
    public int getSize(){
        return array.getSize();
    }

    @Override
    public boolean isEmpty(){
        return array.isEmpty();
    }

    public int getCapacity(){
        return array.getCapacity();
    }

    @Override
    public void enqueue(E e){
        array.addLast(e);
    }

    @Override
    public E dequeue(){
        return array.removeFirst();
    }

    @Override
    public E getFront(){
        return array.getFirst();
    }

    @Override
    public String toString(){
        StringBuilder res = new StringBuilder();
        res.append("Queue: ");
        res.append("front [");
        for(int i = 0 ; i < array.getSize() ; i ++){
            res.append(array.get(i));
            if(i != array.getSize() - 1)
                res.append(", ");
        }
        res.append("] tail");
        return res.toString();
    }

    public static void main(String[] args) {

        ArrayQueue<Integer> queue = new ArrayQueue<>();
        for(int i = 0 ; i < 10 ; i ++){
            queue.enqueue(i);
            System.out.println(queue);
            if(i % 3 == 2){
                queue.dequeue();
                System.out.println(queue);
            }
        }
    }
}

Array.java:

public class Array<E> {

    private E[] data;
    private int size;

    // 構造函數,傳入數組的容量capacity構造Array
    public Array(int capacity){
        data = (E[])new Object[capacity];
        size = 0;
    }

    // 無參數的構造函數,默認數組的容量capacity=10
    public Array(){
        this(10);
    }

    // 獲取數組的容量
    public int getCapacity(){
        return data.length;
    }

    // 獲取數組中的元素個數
    public int getSize(){
        return size;
    }

    // 返回數組是否爲空
    public boolean isEmpty(){
        return size == 0;
    }

    // 在index索引的位置插入一個新元素e
    public void add(int index, E e){

        if(index < 0 || index > size)
            throw new IllegalArgumentException("Add failed. Require index >= 0 and index <= size.");

        if(size == data.length)
            resize(2 * data.length);

        for(int i = size - 1; i >= index ; i --)
            data[i + 1] = data[i];

        data[index] = e;

        size ++;
    }

    // 向所有元素後添加一個新元素
    public void addLast(E e){
        add(size, e);
    }

    // 在所有元素前添加一個新元素
    public void addFirst(E e){
        add(0, e);
    }

    // 獲取index索引位置的元素
    public E get(int index){
        if(index < 0 || index >= size)
            throw new IllegalArgumentException("Get failed. Index is illegal.");
        return data[index];
    }

    public E getLast(){
        return get(size - 1);
    }

    public E getFirst(){
        return get(0);
    }

    // 修改index索引位置的元素爲e
    public void set(int index, E e){
        if(index < 0 || index >= size)
            throw new IllegalArgumentException("Set failed. Index is illegal.");
        data[index] = e;
    }

    // 查找數組中是否有元素e
    public boolean contains(E e){
        for(int i = 0 ; i < size ; i ++){
            if(data[i].equals(e))
                return true;
        }
        return false;
    }

    // 查找數組中元素e所在的索引,如果不存在元素e,則返回-1
    public int find(E e){
        for(int i = 0 ; i < size ; i ++){
            if(data[i].equals(e))
                return i;
        }
        return -1;
    }

    // 從數組中刪除index位置的元素, 返回刪除的元素
    public E remove(int index){
        if(index < 0 || index >= size)
            throw new IllegalArgumentException("Remove failed. Index is illegal.");

        E ret = data[index];
        for(int i = index + 1 ; i < size ; i ++)
            data[i - 1] = data[i];
        size --;
        data[size] = null; // loitering objects != memory leak

        if(size == data.length / 4 && data.length / 2 != 0)
            resize(data.length / 2);
        return ret;
    }

    // 從數組中刪除第一個元素, 返回刪除的元素
    public E removeFirst(){
        return remove(0);
    }

    // 從數組中刪除最後一個元素, 返回刪除的元素
    public E removeLast(){
        return remove(size - 1);
    }

    // 從數組中刪除元素e
    public void removeElement(E e){
        int index = find(e);
        if(index != -1)
            remove(index);
    }

    @Override
    public String toString(){

        StringBuilder res = new StringBuilder();
        res.append(String.format("Array: size = %d , capacity = %d\n", size, data.length));
        res.append('[');
        for(int i = 0 ; i < size ; i ++){
            res.append(data[i]);
            if(i != size - 1)
                res.append(", ");
        }
        res.append(']');
        return res.toString();
    }

    // 將數組空間的容量變成newCapacity大小
    private void resize(int newCapacity){

        E[] newData = (E[])new Object[newCapacity];
        for(int i = 0 ; i < size ; i ++)
            newData[i] = data[i];
        data = newData;
    }
}

在這個實現中,隊列的dequeue操作的效率是比較低的,因爲每一次dequeue操作,都需要把數組中的其他元素往前挪一位,算法的複雜度是O(n)。這個問題可以使用循環隊列的實現進行優化處理,以下是循環隊列的一種實現。

循環隊列

LoopQueue.java

public class LoopQueue<E> implements Queue<E> {

    private E[] data;
    private int front, tail;
    private int size;  //

    public LoopQueue(int capacity){
        data = (E[])new Object[capacity + 1];
        front = 0;
        tail = 0;
        size = 0;
    }

    public LoopQueue(){
        this(10);
    }

    public int getCapacity(){
        return data.length - 1;
    }

    @Override
    public boolean isEmpty(){
        return front == tail;
    }

    @Override
    public int getSize(){
        return size;
    }

    @Override
    public void enqueue(E e){

        if((tail + 1) % data.length == front)
            resize(getCapacity() * 2);

        data[tail] = e;
        tail = (tail + 1) % data.length;
        size ++;
    }

    @Override
    public E dequeue(){

        if(isEmpty())
            throw new IllegalArgumentException("Cannot dequeue from an empty queue.");

        E ret = data[front];
        data[front] = null;
        front = (front + 1) % data.length;
        size --;
        if(size == getCapacity() / 4 && getCapacity() / 2 != 0)
            resize(getCapacity() / 2);
        return ret;
    }

    @Override
    public E getFront(){
        if(isEmpty())
            throw new IllegalArgumentException("Queue is empty.");
        return data[front];
    }

    private void resize(int newCapacity){

        E[] newData = (E[])new Object[newCapacity + 1];
        for(int i = 0 ; i < size ; i ++)
            newData[i] = data[(i + front) % data.length];

        data = newData;
        front = 0;
        tail = size;
    }

    @Override
    public String toString(){

        StringBuilder res = new StringBuilder();
        res.append(String.format("Queue: size = %d , capacity = %d\n", size, getCapacity()));
        res.append("front [");
        for(int i = front ; i != tail ; i = (i + 1) % data.length){
            res.append(data[i]);
            if((i + 1) % data.length != tail)
                res.append(", ");
        }
        res.append("] tail");
        return res.toString();
    }

    public static void main(String[] args){

        LoopQueue<Integer> queue = new LoopQueue<>();
        for(int i = 0 ; i < 10 ; i ++){
            queue.enqueue(i);
            System.out.println(queue);

            if(i % 3 == 2){
                queue.dequeue();
                System.out.println(queue);
            }
        }
    }
}

在這個例子中,並不需要每次dequeue都需要移動數組的元素,使用front和tail,分別指向隊列首尾的位置。只有當隊列的數據數量等於容量的1/4時,纔會觸發縮小容量的操作,使用均攤複雜度分析,複雜度是O(n)。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章