LinkedList 的實現原理

一寸HUI發表於2021-02-18

本文為部落格園作者所寫: 一寸HUI,個人部落格地址:https://www.cnblogs.com/zsql/

簡單的一個類就直接說了。LinkedList 的底層結構是一個帶頭/尾指標的雙向連結串列,可以快速的對頭/尾節點 進行操作,它允許插 入所有元素,包括 null。 相比陣列(這裡可以對比ArrayList原始碼分析進行檢視),連結串列的特點就是在指定位置插入和刪除元素的效率較高,但是查詢的 效率就不如陣列那麼高了。如果熟悉雙向連結串列這個資料結構,其實就很簡單了,無非就是實現一些資料的新增,刪除,查詢,遍歷等功能,雙向連結串列的結構圖如下:

 

 

每一個資料(節點)都包含3個部分,一個是資料本身item,一個是指向下一個節點的next指標,還有就是指向上一個節點的prev指標,另外,雙向連結串列還有一個 first 指標,指向頭節點,和 last 指標,指向尾節點。,在LinkedList類中通過私有的靜態內部類Node作為每一個資料的封裝。具體實現如下:

private static class Node<E> {  //這個類就是用來封裝雙向連結串列中的每一個資料,也是上圖中的每一個框
        E item;
        Node<E> next;
        Node<E> prev;

        Node(Node<E> prev, E element, Node<E> next) {
            this.item = element;
            this.next = next;
            this.prev = prev;
        }
    }

接下看看LinkList類的定義:

public class LinkedList<E>
    extends AbstractSequentialList<E> //繼承的類
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable //實現的各種介面
{}

 

 

 接下來看看LinkedList這個類的一些屬性:就三個屬性,一個用來記錄雙向連結串列的大小,一個是first節點用來指向連結串列的頭,last用來指向連結串列的尾

   transient int size = 0;

    /**
     * Pointer to first node.
     * Invariant: (first == null && last == null) ||
     *            (first.prev == null && first.item != null)
     */
    transient Node<E> first;

    /**
     * Pointer to last node.
     * Invariant: (first == null && last == null) ||
     *            (last.next == null && last.item != null)
     */
    transient Node<E> last;

在看看構造方法:

/**
     * Constructs an empty list.
     */
    public LinkedList() { //空參構造
    }

/**
     * Constructs a list containing the elements of the specified
     * collection, in the order they are returned by the collection's
     * iterator.
     *
     * @param  c the collection whose elements are to be placed into this list
     * @throws NullPointerException if the specified collection is null
     */
    public LinkedList(Collection<? extends E> c) { //通過已有的集合進行構造
        this();
        addAll(c); //使用addAll()方法把集合中的資料生產LinkedList
    }

public boolean addAll(Collection<? extends E> c) {
        return addAll(size, c);
    }

public boolean addAll(int index, Collection<? extends E> c) {
        checkPositionIndex(index);

        Object[] a = c.toArray(); //把集合轉為陣列
        int numNew = a.length;
        if (numNew == 0)
            return false;

        Node<E> pred, succ;
        if (index == size) {
            succ = null;
            pred = last;
        } else {
            succ = node(index);
            pred = succ.prev;
        }

        for (Object o : a) { //對陣列進行遍歷,對每一個元素都封裝成Node並新增到LinkedList中
            @SuppressWarnings("unchecked") E e = (E) o;
            Node<E> newNode = new Node<>(pred, e, null);
            if (pred == null)
                first = newNode;
            else
                pred.next = newNode;
            pred = newNode;
        }

        if (succ == null) {
            last = pred;
        } else {
            pred.next = succ;
            succ.prev = pred;
        }

        size += numNew;
        modCount++;
        return true;
    }

接下來看看LinkedList的基本操作,新增,刪除,遍歷,查詢等

先看新增,從雙向連結串列的結構來看,新增元素可以在連結串列的頭、尾、以及中間的任意位置新增新的元素。因為 LinkedList 有頭指標和尾指標,所以在表頭或表尾進 行插入元素只需要 O(1) 的時間,而在指定位置插入元素則需要先遍歷一下連結串列, 所以複雜度為 O(n)。首先看看在頭部新增元素:

 

 

 看圖可以看出,只要把first指向新的node,新的node的next指向原先firt指向的node,再把原先first指向的node的prev指向新的node就可以了。

/**
     * Links e as first element.
     */
    private void linkFirst(E e) {
        final Node<E> f = first; //使用臨時node
        final Node<E> newNode = new Node<>(null, e, f); //封裝新的node,並把新node的nex指向f
        first = newNode;
        if (f == null) //判斷first是否為空
            last = newNode;
        else
            f.prev = newNode; //把f的prev指向新的node
        size++; //連結串列長度加1
        modCount++; //記錄連結串列被修改的次數
    }

在看看在尾部新增,其實和在頭部新增一樣,只是把first換成了last,邏輯一樣

/**
     * Links e as last element.
     */
    void linkLast(E e) {
        final Node<E> l = last;
        final Node<E> newNode = new Node<>(l, e, null);
        last = newNode;
        if (l == null)
            first = newNode;
        else
            l.next = newNode;
        size++;
        modCount++;
    }

再看看在中間的任意位置新增:

 

 

 這個相對來說複雜點點,修改新增前後node的next和prev的指向,修改的相對來說多點點

/**
     * Inserts element e before non-null Node succ.
     */
    void linkBefore(E e, Node<E> succ) { //表示在在succ節點前面新增e元素
        // assert succ != null;
        final Node<E> pred = succ.prev; //獲取succ的前面節點
        final Node<E> newNode = new Node<>(pred, e, succ); //把e封裝成節點,並把prev指向succ前面節點,把next指向succ節點
        succ.prev = newNode; //然後把succ的prev指向新的節點
        if (pred == null)
            first = newNode;
        else
            pred.next = newNode; //把succ的前節點的next只想新的節點
        size++; //連結串列長度+1
        modCount++; //修改次數+1
    }

新增說完了,就說說刪除,其實也很簡單

 

 

 刪除也是分為從頭部、尾部、中間位置刪除

先看看從first位置刪除

/**
     * Unlinks non-null first node f. 
     */
    private E unlinkFirst(Node<E> f) { 
        // assert f == first && f != null; 
        final E element = f.item; //獲取first中間的元素,用於後面的返回
        final Node<E> next = f.next; //獲取f的next節點
        f.item = null;
        f.next = null; // help GC 清除
        first = next; //把first指向f的next
        if (next == null)
            last = null;
        else
            next.prev = null;  //清除
        size--; //連結串列長度-1
        modCount++; //修改次數+1
        return element;
    }

看了從頭部刪除,其實尾部刪除也差不多

 /**
     * Unlinks non-null last node l.
     */
    private E unlinkLast(Node<E> l) {
        // assert l == last && l != null;
        final E element = l.item;
        final Node<E> prev = l.prev;
        l.item = null;
        l.prev = null; // help GC
        last = prev;
        if (prev == null)
            first = null;
        else
            prev.next = null;
        size--;
        modCount++;
        return element;
    }

在看看從指定位置刪除吧

/**
     * Unlinks non-null node x.
     */
    E unlink(Node<E> x) {
        // assert x != null;
        final E element = x.item; //獲取該節點的值
        final Node<E> next = x.next; //獲取該節點的next節點
        final Node<E> prev = x.prev; //獲取該節點的prev節點

        if (prev == null) { //把該節點的前節點的next指向該節點的next節點,並清除該節點的prev指向
            first = next;
        } else {
            prev.next = next;
            x.prev = null;
        }

        if (next == null) { //把該節點的next節點的prev指向該節點的prev節點,並清除該節點的next指向
            last = prev;
        } else {
            next.prev = prev;
            x.next = null;
        }

        x.item = null; //清除
        size--; //連結串列長度-1
        modCount++; //修改次數+1
        return element;
    }

看完增刪,那就繼續看查相關的方法,也有從頭,尾相關的查詢方法,都很簡單,做判斷,然後查詢

/**
     * Returns the first element in this list.
     *
     * @return the first element in this list
     * @throws NoSuchElementException if this list is empty
     */
    public E getFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return f.item;
    }

    /**
     * Returns the last element in this list.
     *
     * @return the last element in this list
     * @throws NoSuchElementException if this list is empty
     */
    public E getLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return l.item;
    }

當然還有指定index查詢的

/**
     * Returns the (non-null) Node at the specified element index.
     */
    Node<E> node(int index) {
        // assert isElementIndex(index);
        //判斷index是在連結串列的前半段還是在後半段,如果在前半段就從first向後遍歷,否則使用last向前遍歷
        if (index < (size >> 1)) { 
            Node<E> x = first;
            for (int i = 0; i < index; i++)
                x = x.next;
            return x;
        } else {
            Node<E> x = last;
            for (int i = size - 1; i > index; i--)
                x = x.prev;
            return x;
        }
    }

其實基本知道了上面的方法基本對雙向連結串列有了一定的熟悉,當然LinkedList還有很多其他的方法,不過很多都是基於上面這些方法的一些封裝,例如:

/**
     * Inserts the specified element at the beginning of this list.
     *
     * @param e the element to add
     */
    public void addFirst(E e) {
        linkFirst(e);
    }

    /**
     * Appends the specified element to the end of this list.
     *
     * <p>This method is equivalent to {@link #add}.
     *
     * @param e the element to add
     */
    public void addLast(E e) {
        linkLast(e);
    }
/**
     * Removes and returns the first element from this list.
     *
     * @return the first element from this list
     * @throws NoSuchElementException if this list is empty
     */
    public E removeFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return unlinkFirst(f);
    }

    /**
     * Removes and returns the last element from this list.
     *
     * @return the last element from this list
     * @throws NoSuchElementException if this list is empty
     */
    public E removeLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return unlinkLast(l);
    }
/**
     * Appends the specified element to the end of this list.
     *
     * <p>This method is equivalent to {@link #addLast}.
     *
     * @param e element to be appended to this list
     * @return {@code true} (as specified by {@link Collection#add})
     */
    public boolean add(E e) {
        linkLast(e);
        return true;
    }
/**
     * Removes the first occurrence of the specified element from this list,
     * if it is present.  If this list does not contain the element, it is
     * unchanged.  More formally, removes the element with the lowest index
     * {@code i} such that
     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>
     * (if such an element exists).  Returns {@code true} if this list
     * contained the specified element (or equivalently, if this list
     * changed as a result of the call).
     *
     * @param o element to be removed from this list, if present
     * @return {@code true} if this list contained the specified element
     */
    public boolean remove(Object o) {
        if (o == null) {
            for (Node<E> x = first; x != null; x = x.next) {
                if (x.item == null) {
                    unlink(x);
                    return true;
                }
            }
        } else {
            for (Node<E> x = first; x != null; x = x.next) {
                if (o.equals(x.item)) {
                    unlink(x);
                    return true;
                }
            }
        }
        return false;
    }
/**
     * Removes all of the elements from this list.
     * The list will be empty after this call returns.
     */
    public void clear() {
        // Clearing all of the links between nodes is "unnecessary", but:
        // - helps a generational GC if the discarded nodes inhabit
        //   more than one generation
        // - is sure to free memory even if there is a reachable Iterator
        for (Node<E> x = first; x != null; ) {
            Node<E> next = x.next;
            x.item = null;
            x.next = null;
            x.prev = null;
            x = next;
        }
        first = last = null;
        size = 0;
        modCount++;
    }
/**
     * Removes the element at the specified position in this list.  Shifts any
     * subsequent elements to the left (subtracts one from their indices).
     * Returns the element that was removed from the list.
     *
     * @param index the index of the element to be removed
     * @return the element previously at the specified position
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E remove(int index) {
        checkElementIndex(index);
        return unlink(node(index));
    }
/**
     * Returns the index of the first occurrence of the specified element
     * in this list, or -1 if this list does not contain the element.
     * More formally, returns the lowest index {@code i} such that
     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
     * or -1 if there is no such index.
     *
     * @param o element to search for
     * @return the index of the first occurrence of the specified element in
     *         this list, or -1 if this list does not contain the element
     */
    public int indexOf(Object o) { //查詢元素o是否在連結串列中,並返回index,沒找到返回-1
        int index = 0;
        if (o == null) {
            for (Node<E> x = first; x != null; x = x.next) {
                if (x.item == null)
                    return index;
                index++;
            }
        } else {
            for (Node<E> x = first; x != null; x = x.next) {
                if (o.equals(x.item))
                    return index;
                index++;
            }
        }
        return -1;
    }

到這裡本文就結束了了,如果想知道LinkedList的更多方法,建議去看原始碼

相關文章