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

代码来源于 JDK7

private void linkFirst(E e) { final Node f = first; final Node 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 item; Node next; Node prev; Node(Node prev, E element, Node next) { this.item = element; this.next = next; this.prev = prev; } }
final Node 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 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 newNode = new Node<>(null, e, f);
    private static class Node {

    E item; Node next; Node prev; Node(Node prev, E element, Node next) { this.item = element; this.next = next; this.prev = prev; } }
      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!