1. public E remove() {
    2. return removeFirst(); //删除第一个元素
    3. }
    1. public E removeFirst() {
    2. final Node<E> f = first;
    3. if (f == null)
    4. throw new NoSuchElementException();
    5. return unlinkFirst(f);
    6. }
    1. private E unlinkFirst(Node<E> f) {
    2. // assert f == first && f != null;
    3. final E element = f.item;
    4. final Node<E> next = f.next;
    5. f.item = null;
    6. f.next = null; // help GC 1
    7. first = next; 2
    8. if (next == null)
    9. last = null;
    10. else
    11. next.prev = null; 3
    12. size--;
    13. modCount++;
    14. return element;
    15. }

    LinkedList删除方法 - 图1

    1. public E removeLast() {
    2. final Node<E> l = last;
    3. if (l == null)
    4. throw new NoSuchElementException();
    5. return unlinkLast(l);
    6. }
    1. private E unlinkLast(Node<E> l) {
    2. // assert l == last && l != null;
    3. final E element = l.item;
    4. final Node<E> prev = l.prev;
    5. l.item = null;
    6. l.prev = null; // help GC 1
    7. last = prev; 2
    8. if (prev == null)
    9. first = null;
    10. else
    11. prev.next = null;
    12. size--;
    13. modCount++;
    14. return element;
    15. }

    LinkedList删除方法 - 图2

    1. public E remove(int index) {
    2. checkElementIndex(index);
    3. return unlink(node(index));
    4. }
    1. E unlink(Node<E> x) {
    2. // assert x != null;
    3. final E element = x.item;
    4. final Node<E> next = x.next;
    5. final Node<E> prev = x.prev;
    6. if (prev == null) { // 如果X为头指针
    7. first = next; // 让first指针指向next
    8. } else {
    9. prev.next = next;
    10. x.prev = null;
    11. }
    12. if (next == null) { // 如果X为尾指针
    13. last = prev; // 让last指针指向prev
    14. } else {
    15. next.prev = prev;
    16. x.next = null;
    17. }
    18. x.item = null;
    19. size--;
    20. modCount++;
    21. return element;
    22. }

    LinkedList删除方法 - 图3

    1. public boolean remove(Object o) {
    2. if (o == null) {
    3. for (Node<E> x = first; x != null; x = x.next) {
    4. if (x.item == null) {
    5. unlink(x);
    6. return true;
    7. }
    8. }
    9. } else {
    10. for (Node<E> x = first; x != null; x = x.next) {
    11. if (o.equals(x.item)) {
    12. unlink(x);
    13. return true;
    14. }
    15. }
    16. }
    17. return false;
    18. }
    1. public void clear() {
    2. // Clearing all of the links between nodes is "unnecessary", but:
    3. // - helps a generational GC if the discarded nodes inhabit
    4. // more than one generation
    5. // - is sure to free memory even if there is a reachable Iterator
    6. // 从头到尾断开所有的引用关系
    7. for (Node<E> x = first; x != null; ) {
    8. Node<E> next = x.next;
    9. x.item = null;
    10. x.next = null;
    11. x.prev = null;
    12. x = next;
    13. }
    14. first = last = null;
    15. size = 0;
    16. modCount++;
    17. }