search

Home  >  Q&A  >  body text

为什么 Java 的 LinkedList 的双链表实现不会链接后面元素

  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++;
    }
阿神阿神2785 days ago919

reply all(2)I'll reply

  • 高洛峰

    高洛峰2017-04-18 10:50:47

    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 元素了。

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-18 10:50:47

    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;
        }
    }

    reply
    0
  • Cancelreply