Java Queue 隊列


隊列是一種先進先出的數據結構,隊列中插入元素和刪除元素分別位於隊列的兩端。 

在Java中 隊列實現類眾多,本文不再贅述。本文探討的是如何自定義隊列實現類:

基於數組方式實現隊列:

注意點:

當出隊時隊首為空,如果不移動隊列元素那么會使得隊尾在插入元素過程中越界,因隊首為空,數組實際使用空間小於數組的大小,所有要移動隊列的元素。

而且每次出隊都要移動,使得耗費大量的時間。

import java.util.Arrays;

public class ArrayQueue<E> {
    Object[] queue;
    int size;

    public ArrayQueue() {
        queue = new Object[10];
    }

    public boolean isEmpty() {
        return size == 0;
    }

    //入隊
    public void offer(E data) {
        ensureCapacity(size+1);
        queue[size++] = data;
    }
    
    //出隊
    public E poll() {
        if (isEmpty()) return null;
        E data = (E) queue[0];
        System.arraycopy(queue, 1, queue, 0, size-1); //填滿空位
        size--;
        return data;
    }
    
    //擴容
    private void ensureCapacity(int size) {
        if (size > queue.length) {
            int len = queue.length + 10;
            queue = Arrays.copyOf(queue, len);
        }
    }

    public static void main(String[] args) {
        ArrayQueue<Integer>  queue = new ArrayQueue<>();

        for (int i = 0; i < 20; i++) {
            queue.offer(i);
        }
        for (int i = 0; i < 10; i++) {
            System.out.println("出隊元素:"+queue.poll());
        }
    }
}

 

基於鏈表實現的隊列

由於鏈表的地址是不連續的的所以無須擴容。出隊和入隊都非常快。

class ListNode<E> {
    ListNode<E> next = null;
    E data;
    public ListNode(E data) {
        this.data = data;
    }
}

public class ListQueue<E> {
    
    private ListNode<E> head = null;        //隊首
    private ListNode<E> end = null;         //隊尾

    public boolean isEmpty() {
        return head == null;
    }

    //入隊
    public void offer(E e) {
        ListNode<E> node = new ListNode<E>(e);
        if (isEmpty()) {
            head = node;
            end = node;
            return;
        }
        end.next = node;
        end = node;
    }

    //出隊
    public E poll() {
        if (isEmpty()) return null;
        E data = head.data;
        head = head.next;
        return data;
    }


    public static void main(String[] args) {
        ListQueue<String> queue = new ListQueue<>();
        System.out.println("入隊");
        queue.offer("first");
        queue.offer("second");
        System.out.println("出隊"+queue.poll());
        System.out.println("出隊"+queue.poll());
    }
}

 


免責聲明!

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



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