1. 程式人生 > 其它 >LinkedList原碼分析和效率分析(一)

LinkedList原碼分析和效率分析(一)

LinkedList原碼分析和效率分析(一)

連結串列(Linked list)是一種常見的基礎資料結構,是一種線性表,但是並不會按線性的順序儲存資料,而是在每一個節點裡存到下一個節點的地址。

連結串列可分為單向連結串列和雙向連結串列。

一個單向連結串列包含兩個值: 當前節點的值和一個指向下一個節點的連結。
img
一個雙向連結串列有三個整數值: 數值、向後的節點連結、向前的節點連結。
img
Java LinkedList(連結串列) 類似於 ArrayList,是一種常用的資料容器。

與 ArrayList 相比,LinkedList 的增加和刪除對操作效率更高,而查詢和修改的操作效率較低。

LinkedList底層的資料結構是基於雙向迴圈連結串列的,且頭結點中不存放資料繼承了AbstractSequentialList抽象類

實現了List、Deque、Cloneable、Serializable接

新增方法:
boolean add(E e);
新增一個新元素直接在最後面新增
 /**
     * 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})
     */
// 將元素(E)新增到LinkedList中 public boolean add(E e) { // 將節點(節點資料是e)新增到表頭(header)之前。 // 即,將節點新增到雙向連結串列的末端。 linkLast(e); return true; }
boolean add(int index, E e)
在指定的位置上新增新的元素。
在方法中先判斷新新增的元素是否是位於LinkedList的最後,然後是,則直接呼叫linkLast()方法新增即可。
 /**
     * Inserts the specified element at the specified position in this list.
     * Shifts the element currently at that position (if any) and any
     * subsequent elements to the right (adds one to their indices).
     *
     * @param index index at which the specified element is to be inserted
     * @param element element to be inserted
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
public void add(int index, E element) { checkPositionIndex(index); if (index == size) linkLast(element); else linkBefore(element, node(index)); }
boolean addFirst(E e);
在LinkedList頭部新增一個新的元素新增一個新元素。
 /**
     * Inserts the specified element at the beginning of this list.
     *
     * @param e the element to add
     */
    public void addFirst(E e) {
        linkFirst(e);
    }
boolean addLast(E e);
在LinkedList尾部新增一個新的元素新增一個新元素。
   /**
     * 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);
    }