跳至主要內容

02-带有头尾指针的链表

Lil-K2024/1/11小于 1 分钟数据结构数据结构链表

带有头尾指针的链表

代码实现

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

    private class Node {
        public E e;
        public Node next;

        public Node () {}

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

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

    private Node head, tail;

    private int size;

    public LinkedListQueue() {
        head = null;
        tail = null;
        size = 0;
    }

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

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

    /**
     * 入队
     * @param e
     */
    @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++;
    }

    /**
     * 出队
     * @return
     */
    @Override
    public E dequeue() {
        if (isEmpty()) {
            throw new IllegalArgumentException("Cannot dequeue from an empty queue.");
        }
        // 记录出队元素
        Node retNode = head;

        // 维护链表 head的位置
        head = head.next;

        // 将出队的位置变为null
        retNode.next = null;

        /**
         * 当队列只剩一个元素时,head.next == null
         * 所以要维护一下 tail
         */
        if (head == null) {
            tail = null;
        }
        size--;
        return (E)retNode.e;
    }

    /**
     * 获取队首元素
     * @return
     */
    @Override
    public E getFront() {
        if (isEmpty()) {
            throw new IllegalArgumentException("Cannot dequeue from an empty queue.");
        }

        return head.e;
    }

    @Override
    public String toString() {
        StringBuilder res = new StringBuilder();
        Node cur = head;
        while (cur != null) {
            res.append(cur + "->");
            cur = cur.next;
        }
        res.append("null tail");
        return res.toString();
    }
}

Your primary language is en-US, do you want to switch to it?

您的首选语言是 en-US,是否切换到该语言?