Java_LinkedList工作原理

Doubly-linked list implementation of the List and Deque interfaces. Implements all optional list operations, and permits all elements (including null).

LinkedList实现了list接口,其底层实际上一个双向链表,其基本操作就是对双向链表的操作。当然,LinkedList是允许添加null的。

简单例子如下:

public class TestLinkList {
    public static void main(String[] args) {
      List<String> list=new LinkedList<String>();
      list.add("A");
      list.add("B");
      list.add(null);
      list.add("C");
    }
}

这里写图片描述

可以查看,链表持有一个first与last节点,分别指向第一个和最后一个节点。对于每个具体的节点,其有next与prev属性,分别指向其下一个节点和上一个节点。
其数据结构图如下:
这里写图片描述
开始的一个第一个节点为空节点,不保存数据。


LinkedList部分源码:

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

    //节点
    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;
        }
    }

    //链表的最后添加节点
    public boolean add(E e) {
        linkLast(e);
        return true;
    }
    //获取指定位置的节点
    public E get(int index) {
        //下标越界检查
        checkElementIndex(index);
        //获取指定位置的数据
        return node(index).item;
    }

    Node<E> node(int index) {
        //如果要获取的下标在size/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 是一个实现了list接口,底层是一个双向链表,基本的操作就是对链表的操作, 因为是基于链表来实现的,所以其容量是无限的, 在get操作的时候,会判断index与链表一般的大小,若index小于size/2,则从表头来开始查找,否则从链表的尾部开始查找

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