線性結(jié)構(gòu):鏈表隊列

思路

由于鏈表只在頭節(jié)點處增刪都為O(1),那么對于隊列操作,采用上一篇的鏈表結(jié)構(gòu),就不能做到入隊和出隊操作都為O(1),假設(shè)在鏈表頭處入隊,那么鏈表尾出隊就為O(n)了,反之亦然。為了解決這個問題,我們需要在將鏈表尾也標(biāo)記出來,記為tail。


截屏2021-01-15 上午8.51.07.png

圖中可以看出,在這個實現(xiàn)中,由于只在頭和尾進行操作,不涉及操作的統(tǒng)一性,因此去掉了dummyHead。

實現(xiàn)

public class LinkedListQueue<E> implements Queue<E> {
    private Node head, tail;
    private int size;

    private class Node {
        E e;
        Node next;

        public Node(E e, Node next) {
            this.e = e;
            this.next = next;
        }

        public Node(E e) {
            this(e, null);
        }

        public Node() {
            this(null, null);
        }
    }

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

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

    @Override
    public void enqueue(E e) {
        if (tail == null) {
            tail = new Node(e);
            head = tail;
        } else {
            tail.next = new Node(e);
            tail = tail.next;
        }
        size++;
    }

    @Override
    public E dequeue() {
        if (isEmpty()) {
            throw new IllegalStateException("Cannot dequeue in a empty queue.");
        }

        Node delNode = head;
        head = head.next;
        delNode.next = null;
        if (head == null) {
            tail = null;
        }
        size--;
        return delNode.e;
    }

    @Override
    public E getFront() {
        if (isEmpty()) {
            throw new IllegalStateException("Cannot read in a empty queue.");
        }

        return head.e;
    }

    @Override
    public String toString() {
        StringBuilder res = new StringBuilder();
        res.append("LinkedListQueue: front ");
        Node curNode = head;
        while (curNode != null) {
            res.append(curNode.e).append(" -> ");
            curNode = curNode.next;
        }
        res.append("tail NULL");
        return res.toString();
    }

    public static void main(String[] args) {
        LinkedListQueue<Integer> queue = new LinkedListQueue<>();
        for (int i = 0; i < 10; i++) {
            queue.enqueue(i);
            System.out.println(queue);
            if ((i + 1) % 3 == 0) {
                queue.dequeue();
                System.out.println(queue);
            }
        }
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容