數(shù)據(jù)結(jié)構(gòu)(二)LinkedList

引言

由上一篇我們知道,ArrayList的優(yōu)勢是查詢速度快,但是插入、刪除相對較慢,那對于需要大量增、刪操作的數(shù)據(jù),該用什么樣的結(jié)構(gòu)呢?

鏈表

單向鏈表

如圖所示,定義一種鏈表結(jié)構(gòu),每一個節(jié)點都持有下一個節(jié)點的引用,當增加元素時,只需要修改當前位置的指向即可,速度就會比ArrayList復(fù)制快。


單向鏈表新增元素

顯然,它有一個弊端,如果我們想獲取最后一個元素,必須從第一個元素一個一個查下去,浪費時間。

為了提高查詢效率,定義如下結(jié)構(gòu):


雙向鏈表

每個元素都持有它前、后兩個元素的引用,在遇到上述問題,會大大縮短查詢時間。

LinkedList源碼

鏈表首、尾節(jié)點的引用:

/**
 * 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;

Node結(jié)構(gòu)

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

添加元素 add -> linkLast

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

/**
 * Links e as last element.
 */
void linkLast(E e) {
    // 取尾部元素
    final Node<E> l = last;
    // 生成新的Node節(jié)點
    final Node<E> newNode = new Node<>(l, e, null);
    // 將尾引用指向新的節(jié)點
    last = newNode;
    if (l == null)// 如果列表中沒有元素,將頭指向新節(jié)點
        first = newNode;
    else// 如果有元素,將新節(jié)點鏈接到隊尾
        l.next = newNode;
    size++;
    modCount++;
}

刪除元素 remove -> unlink

public boolean remove(Object o) {
    if (o == null) {
        // 遍歷刪除null
        for (Node<E> x = first; x != null; x = x.next) {
            if (x.item == null) {
                unlink(x);
                return true;
            }
        }
    } else {
        // 遍歷找到equals的對象
        for (Node<E> x = first; x != null; x = x.next) {
            if (o.equals(x.item)) {
                unlink(x);
                return true;
            }
        }
    }
    return false;
}

E unlink(Node<E> x) {
    // assert x != null;
    // 獲取當前節(jié)點的前后節(jié)點
    final E element = x.item;
    final Node<E> next = x.next;
    final Node<E> prev = x.prev;

    // 刪除跟上個節(jié)點的關(guān)系
    if (prev == null) {
        first = next;
    } else {
        prev.next = next;
        x.prev = null;
    }

    // 刪除跟下個節(jié)點的關(guān)系
    if (next == null) {
        last = prev;
    } else {
        next.prev = prev;
        x.next = null;
    }

    // 刪除數(shù)據(jù)
    x.item = null;
    size--;
    modCount++;
    return element;
}

查詢數(shù)據(jù) get -> node

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

Node<E> node(int index) {
    // assert isElementIndex(index);
    // 判斷index是否<總個數(shù)/2
    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插入一定比ArrayList快嗎?

大家不妨跑跑下面的代碼:

public class MyTest {
    private static ArrayList<Integer> testArray = new ArrayList<>();
    private static LinkedList<Integer> testLinked = new LinkedList<>();

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        for (int i = 0; i < 10000000; i++) {
            testArray.add(i);
        }
        System.out.println("AAAAA test array time:" + (System.currentTimeMillis() - start));

        start = System.currentTimeMillis();
        for (int i = 0; i < 10000000; i++) {
            testLinked.add(i);
        }
        System.out.println("AAAAA test linked time:" + (System.currentTimeMillis() - start));
    }

}

這是我跑了幾次的結(jié)果

AAAAA test array time:1233
AAAAA test linked time:2396

AAAAA test array time:833
AAAAA test linked time:2312

AAAAA test array time:824
AAAAA test linked time:2242

于是得出以下結(jié)論,在涉及大量數(shù)據(jù)的增加(直接增加,插入末尾)且很少涉及刪除的操作時,ArrayList速度反而更快。

為什么會如此呢?可能與以下代碼有關(guān):


LinkedList添加元素時,創(chuàng)建新的Node

LinkedList每次add時,便創(chuàng)建一個Node對象,增大了時間開銷。

最后編輯于
?著作權(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)容