为什么 Java 的 LinkedList 的双链表实现不会链接后面元素
阿神
阿神 2017-04-18 10:48:47
0
2
915
  1. JDK7中 LinkedList private 方法 private void linkFirst(E e)在新添加元素时链表不会断裂?

代码来源于 JDK7

 private void linkFirst(E e) {
        final Node<E> f = first;
        final Node<E> newNode = new Node<>(null, e, f);
        first = newNode;
        if (f == null)
            last = newNode;
        else
            f.prev = newNode;
           // 此处没有执行 newNode.next = f; newNode.next 不会链接后面的元素
        size++;
        modCount++;
    }
阿神
阿神

闭关修行中......

reply all(2)
小葫芦
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;
    }
}
final Node<E> newNode = new Node<>(null, e, f); // 构造函数的第3个参数不就是 next 元素了。
大家讲道理

Why is the link broken?
f points to the original first and sets the new newNode to first.
At this time, it is judged that if the original linked list is empty, then last is also first.
If it is not empty, then the prev of f<original first node> points to first.


I guess the reason why you think the link is broken is because you didn't see that first's next points to f. Um, next has been passed into Node
final Node<E> newNode = new Node<>(null, e, f);
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;
    }
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template