publicvoidadd(int index, E element) { checkPositionIndex(index);
if (index == size) linkLast(element); else linkBefore(element, node(index)); }
voidlinkLast(E e) { final Node<E> l = last; final Node<E> newNode = newNode<>(l, e, null); last = newNode; if (l == null) first = newNode; else l.next = newNode; size++; modCount++; }
voidlinkBefore(E e, Node<E> succ) { // assert succ != null; final Node<E> pred = succ.prev; final Node<E> newNode = newNode<>(pred, e, succ);
// 建立后链 succ.prev = newNode; // 建立前链 if (pred == null) first = newNode; else pred.next = newNode;
publicbooleanremove(Object o) { if (o == null) { for (Node<E> x = first; x != null; x = x.next) { if (x.item == null) { unlink(x); returntrue; } } } else { for (Node<E> x = first; x != null; x = x.next) { if (o.equals(x.item)) { unlink(x); returntrue; } } } returnfalse; }
E unlink(Node<E> x) { // assert x != null; finalEelement= x.item; final Node<E> next = x.next; final Node<E> prev = x.prev; // 解开前链 if (prev == null) { first = next; } else { prev.next = next; x.prev = null; } // 解开后链 if (next == null) { last = prev; } else { next.prev = prev; x.next = null; }
public E next() { checkForComodification(); if (!hasNext()) thrownewNoSuchElementException(); // 添加previous指向前一个元素 lastReturned = previous = next; next = next.next;
nextIndex++; return lastReturned.item; }
public E previous() { checkForComodification(); if (!hasPrevious()) thrownewNoSuchElementException(); // 添加previous指向前一个元素 lastReturned = next = previous; previous = previous.prev; nextIndex--; return lastReturned.item; } }