[Series] JAVA- most complete source code parsing container articles -LinkedList

Brief introduction

LinkedList name suggests it is essentially a linked list, a doubly linked list specifically, while there are two corresponding head and tail pointers of a linked list.

Source

Source code is still the same with ArrayList, from our usual code:

List<String> a = new LinkedList<>();
a.add("sidfate");
复制代码

Enter initialization Source:

// LinkedList 长度
transient int size = 0;

// 指向头结点
transient Node<E> first;

// 指向尾节点
transient Node<E> last;

public LinkedList() {
}
复制代码

You can see the empty default constructor, to note that the list is based on connecting Node, Node is structured as follows:

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;
    }
}
复制代码

Node structure is very simple, prev and next that it is a two-way linked list, save the Node pointer around. Then add into the process of:

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

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++;
}
复制代码

In simple terms, add an element to the end of the list is to insert a new Node. Well, if it is to insert an element to the list:

public void add(int index, E element) {
    // 检查index合法性
    checkPositionIndex(index);

    if (index == size)
        // 如果index就是尾部则直接添加
        linkLast(element);
    else
        // 在 index 所在的 Node 前插入
        linkBefore(element, node(index));
}

Node<E> node(int index) {
    // assert isElementIndex(index);

    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;
    }
}
复制代码

function is used to find the corresponding node index of node Node, more interesting is reduced by half 2 will traverse the length of the list would be:

  • If the index between the head and the midpoint, then traverse from the beginning to the midpoint.
  • If the midpoint between the index and the tail, the tail then traversing to the midpoint.

Advantages doubly linked list on the prominent, inserted relatively efficient than ArrayList, ArrayList, after all, need to copy the array index. However, the query efficiency is low, the element can be taken out directly from the ArrayList subscripts, and so on because the memory array is continuous, like a series LinkedList The pointer may be discontinuous on the memory address.

There is an advantage when it not only when the queue when stack can also be used in the LinkedList.

Guess you like

Origin juejin.im/post/5e50d7805188254945386262