if (index < (size >> 1)) { Node<E> x = first; for (inti=0; i < index; i++) x = x.next; return x; } else { Node<E> x = last; for (inti= size - 1; i > index; i--) x = x.prev; return x; } }
privatevoidlinkFirst(E e) { final Node<E> f = first; final Node<E> newNode = newNode<>(null, e, f); first = newNode; if (f == null) last = newNode; else f.prev = newNode; size++; modCount++; }
publicbooleanaddAll(int index, Collection<? extends E> c) { // 校验索引合法性 checkPositionIndex(index);
Object[] a = c.toArray(); // 要插入到数据量 intnumNew= a.length; if (numNew == 0) returnfalse; // 声明前置与后置节点 Node<E> pred, succ; if (index == size) { // 说明要从队尾开始插入 succ = null; pred = last; // 此时pred就是最后一个Node } else { // 否则,从指定位置开始插入,此时pred是插入位置Node succ = node(index); pred = succ.prev; } // 遍历集合,将元素依次放入队尾 for (Object o : a) { @SuppressWarnings("unchecked")Ee= (E) o; Node<E> newNode = newNode<>(pred, e, null); if (pred == null) first = newNode; else pred.next = newNode; pred = newNode; } // 变更指针 if (succ == null) { last = pred; } else { pred.next = succ; succ.prev = pred; }
size += numNew; modCount++; returntrue; }
删除操作
remove()
删除队首的数据。将first指向的节点数据删除,同时将first指向节点的next节点作为首节点。
1 2 3
public E remove() { return removeFirst(); }
1 2 3 4 5 6
public E removeFirst() { final Node<E> f = first; if (f == null) thrownewNoSuchElementException(); return unlinkFirst(f); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
private E unlinkFirst(Node<E> f) { // assert f == first && f != null; finalEelement= f.item; final Node<E> next = f.next; f.item = null; f.next = null; // help GC first = next; if (next == null) last = null; else next.prev = null; size--; modCount++; return element; }
remove(int index)
删除指定位置的节点,同时将删除节点的上下游节点关联起来。
1 2 3 4 5
public E remove(int index) { // 校验索引是否合法 checkElementIndex(index); return unlink(node(index)); }
publicbooleanremove(Object o) { if (o == null) { // null要特殊处理 for (Node<E> x = first; x != null; x = x.next) { if (x.item == null) { // 底层还是调用unlinx()方法 unlink(x); returntrue; } } } else { for (Node<E> x = first; x != null; x = x.next) { if (o.equals(x.item)) { unlink(x); returntrue; } } } returnfalse; }
数据访问
get(index)
获取指定索引的值。
1 2 3 4 5 6
public E get(int index) { // 校验索引 checkElementIndex(index); // node方法获取指定位置的值,前面已解释过,这里不多说 return node(index).item; }
poll()
移除并返回链表的第一个元素
1 2 3 4
public E poll() { final Node<E> f = first; return (f == null) ? null : unlinkFirst(f); }
pop()
移除并返回链表的第一个元素
1 2 3
public E pop() { return removeFirst(); }
peek()
返回链表头部的元素
1 2 3 4
public E peek() { final Node<E> f = first; return (f == null) ? null : f.item; }