/** * Pointer to first node. * Invariant: (first == null && last == null) || * (first.prev == null && first.item != null) */ transient Node<E> first;
/** * Pointer to last node. * Invariant: (first == null && last == null) || * (last.next == null && last.item != null) */ transient Node<E> last;
/** * Constructs an empty list. */ publicLinkedList(){ }
/** * Constructs a list containing the elements of the specified * collection, in the order they are returned by the collection's * iterator. * * @param c the collection whose elements are to be placed into this list * @throws NullPointerException if the specified collection is null */ publicLinkedList(Collection<? extends E> c){ this(); addAll(c); }
/** * 因为数据结构不大一样 所以add方式也不一样 * remove方式 实现方式有一点不一样 */ /** * JDK1.8 节点Node * Links e as last element. */ voidlinkLast(E e){ final Node<E> l = last; final Node<E> newNode = new Node<>(l, e, null); last = newNode; if (l == null) first = newNode; else l.next = newNode; size++; modCount++; } /** * Unlinks non-null node x. */ E unlink(Node<E> x){ // assert x != null; final E element = 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; }
/** * 源码中先将index与长度size的一半比较,if index < (size >> 1),就只从位置0往后遍历到位置index处, * 而如果index > (size >> 1),就只从位置size往前遍历到位置index处。 * 这样可以减少一部分不必要的遍历,从而提高一定的效率(实际上效率还是很低)。 * JDK1.8这里用的是位运算 , 而JDK1.6 用的是判断index<size/2 * Returns the (non-null) Node at the specified element index. */ Node<E> node(int index){ // assert isElementIndex(index);
if (index < (size >> 1)) { Node<E> x = first; for (int i = 0; i < index; i++) x = x.next; return x; } else { Node<E> x = last; for (int i = size - 1; i > index; i--) x = x.prev; return x; } }