集合系列 List:LinkedList

LinkedList 是鏈表的經典實現,其底層採用鏈表節點的方式實現。

public class LinkedList<E>
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable

從類繼承結構圖可以看到,LinkedList 不僅實現了 List 接口,還實現了 Deque 雙向隊列接口。

原理

爲了深入理解 LinkedList 的原理,我們將從類成員變量、構造方法、核心方法兩個方面逐一介紹。

類成員變量

// 鏈表大小
transient int size = 0;
// 首節點
transient Node<E> first;
// 尾節點
transient Node<E> last;
// 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;
    }
}

其採用了鏈表節點的方式實現,並且每個節點都有前驅和後繼節點。

構造方法

LinkedList 總共有 2 個構造方法:

public LinkedList() {
}
public LinkedList(Collection<? extends E> c) {
    this();
    addAll(c);
}

構造方法比較簡單,這裏不深入介紹。

核心方法

在 LinkedList 中最爲核心的是查找、插入、刪除、擴容這幾個方法。

查找

LinkedList 底層基於鏈表結構,無法向 ArrayList 那樣隨機訪問指定位置的元素。LinkedList 查找過程要稍麻煩一些,需要從鏈表頭結點(或尾節點)向後查找,時間複雜度爲 O(N)。相關源碼如下:

public E get(int index) {
    checkElementIndex(index);
    return node(index).item;
}

Node<E> node(int index) {
    /*
     * 如果獲取的元素小於容量的一般,則從頭結點開始查找,否則從尾節點開始查找。
     */    
    if (index < (size >> 1)) {
        Node<E> x = first;
        // 循環向後查找,直至 i == index
        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;
    }
}

上面的代碼比較簡單,主要是通過遍歷的方式定位目標位置的節點。獲取到節點後,取出節點存儲的值返回即可。這裏面有個小優化,即通過比較 index 與節點數量 size/2 的大小,決定從頭結點還是尾節點進行查找。

插入

LinkedList 除了實現了 List 接口相關方法,還實現了 Deque 接口的很多方法,例如:addFirst、addLast、offerFirst、offerLast 等。但這些方法的實現思路大致都是一樣的,所以我只講 add 方法的實現。

add 方法有兩個方法,一個是直接插入隊尾,一個是插入指定位置。

我們先來看第一個add方法:直接插入隊列。

public boolean add(E e) {
    linkLast(e);
    return true;
}

可以看到其直接調用了 linkLast 方法,其實它就是 Deque 接口的一個方法。

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++;
}

上述代碼進行了節點的創建以及引用的變化,最後增加鏈表的大小。

我們繼續看第二個add方法:插入指定位置。

public void add(int index, E element) {
    checkPositionIndex(index);

    if (index == size)
        linkLast(element);
    else
        linkBefore(element, node(index));
}

如果我們插入的位置還是鏈表尾部,那麼還是會調用 linkLast 方法。否則調用 node 方法取出插入位置的節點,否則調用 linkBefore 方法插入。

void linkBefore(E e, Node<E> succ) {
    // assert succ != null;
    final Node<E> pred = succ.prev;
    final Node<E> newNode = new Node<>(pred, e, succ);
    succ.prev = newNode;
    if (pred == null)
        first = newNode;
    else
        pred.next = newNode;
    size++;
    modCount++;
}

上述代碼進行了節點的創建以及引用的變化,最後增加鏈表的大小。在這裏插入圖片描述

刪除

刪除節點有兩個方法,第一個是移除特定的元素,第二個是移除某個位置的元素。

我們先看第一個刪除方法:移除特定的元素。。

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;
}

上述代碼的大致思路爲:遍歷找到刪除的節點,之後調用 unlink() 方法解除引用。我們繼續看看 unlink() 方法的代碼。

E unlink(Node<E> x) {
    // assert x != null;
    final E element = x.item;
    final Node<E> next = x.next;
    final Node<E> prev = x.prev;

    if (prev == null) {
        first = next;
    } else {
        prev.next = next;
        x.prev = null;
    }

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

    x.item = null;
    size--;
    modCount++;
    return element;
}

unlink() 代碼裏就是做了一系列的引用修改操作。下面的步驟圖非常詳細地解釋了整個刪除過程。在這裏插入圖片描述
本文圖片來源於田小波的博客

總結

經過上面的分析,我們可以知道 LinkedList 有如下特點:

  • 底層基於鏈表實現,修改速度快,讀取速度慢(讀取時間複雜度O(N),修改時間複雜度O(N),因爲要查找元素,所以修改也是O(N))。
  • 非線程安全。
  • 與 ArrayList 不同,LinkedList 沒有容量限制,所以也沒有擴容機制。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章