LinkedList中removeFirst()底層源碼分析

LinkedList底層是鏈表結構

​
public E removeFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return unlinkFirst(f);
}

first指向鏈表中的第一個結點,那麼接下來看看unlinkFirst(f)方法實現:

先看一下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;
        }
}

item:當前結點中的數據;next:當前結點的下一個結點;prev:當前結點的前一個結點

private E unlinkFirst(Node<E> f) {
        // assert f == first && f != null;    
        //獲取當前結點的元素
        final E element = f.item;
        //獲取當前結點的下一個結點
        final Node<E> next = f.next;
        f.item = null;
        f.next = null; // help GC
        //因爲刪除當前結點元素(第一個結點),所以此處將下一個結點賦值給第一個
        first = next;
        //判斷,如果沒有下一個結點,那麼最後一個結點就不存在,null
        if (next == null)
            last = null;
        else
            //此處的next.prev即第一個結點,要刪除,所以賦值爲null
            next.prev = null;
        //鏈表大小減一
        size--;
        modCount++;
        //將要刪除的元素返回
        return element;
}

如有不當之處,還望賜教!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章