1. public boolean add(E e) {
    2. linkLast(e);
    3. return true;
    4. }
    1. void linkLast(E e) {
    2. final Node<E> l = last;
    3. final Node<E> newNode = new Node<>(l, e, null);
    4. last = newNode;
    5. if (l == null)
    6. first = newNode;
    7. else
    8. l.next = newNode;
    9. size++;
    10. modCount++;
    11. }
    1. public void add(int index, E element) {
    2. checkPositionIndex(index);
    3. if (index == size)
    4. linkLast(element);
    5. else
    6. linkBefore(element, node(index));
    7. }
    1. void linkBefore(E e, Node<E> succ) {
    2. // assert succ != null;
    3. final Node<E> pred = succ.prev;
    4. // 初始化节点,并指明前驱和后继节点
    5. final Node<E> newNode = new Node<>(pred, e, succ);
    6. // 将succ节点前驱引用prev指向新节点
    7. succ.prev = newNode;
    8. // 判断尾节点是否为空,为空表示当前链表没有节点
    9. if (pred == null)
    10. first = newNode;
    11. else
    12. pred.next = newNode; // succ节点前驱的后继引用指向新节点
    13. size++;
    14. modCount++;
    15. }

    LinkedList新增元素的逻辑流程
    (1)创建新节点,并指明新节点的前驱和后继
    (2)将succ的前驱引用指向新节点
    (3)如果succ的前驱不为空,则将succ前驱的后继引用指向新节点

    1. public boolean addAll(int index, Collection<? extends E> c) {
    2. checkPositionIndex(index);
    3. Object[] a = c.toArray();
    4. int numNew = a.length;
    5. if (numNew == 0)
    6. return false;
    7. Node<E> pred, succ;
    8. if (index == size) {
    9. succ = null;
    10. pred = last;
    11. } else {
    12. succ = node(index);
    13. pred = succ.prev;
    14. }
    15. for (Object o : a) {
    16. @SuppressWarnings("unchecked") E e = (E) o; //注解抑制没有进行类型检查操作的警告
    17. Node<E> newNode = new Node<>(pred, e, null);
    18. //让前驱节点连接新节点
    19. if (pred == null) //如果插入节点为第一个节点
    20. first = newNode;
    21. else
    22. pred.next = newNode;
    23. pred = newNode;
    24. }
    25. // 上面先将前驱与新节点连接 接下来 最后一个新节点连接后继节点(succ节点 或 last节点)
    26. if (succ == null) {
    27. last = pred;
    28. } else {
    29. pred.next = succ;
    30. succ.prev = pred;
    31. }
    32. size += numNew;
    33. modCount++;
    34. return true;
    35. }