//将一个元素链接到首位 privatevoidlinkFirst(E e){ //先将原链表存起来 final Node<E> f = first; //定义一个新节点,其next指向原来的first final Node<E> newNode = new Node<>(null, e, f); //将first指向新建的节点 first = newNode; //原链表为空表 if (f == null) //把last也指向新建的节点,现在first与last都指向了它 last = newNode; else //把原链表挂载在新建节点,也就是现在的first之后 f.prev = newNode; size++; modCount++; }
//与linkFirst类似 voidlinkLast(E e){ //... }
//在某个非空节点之前添加元素 voidlinkBefore(E e, Node<E> succ){ // assert succ != null; //先把succ节点的前置节点存起来 final Node<E> pred = succ.prev; //新节点插在pred与succ之间 final Node<E> newNode = new Node<>(pred, e, succ); //succ的prev指针移到新节点 succ.prev = newNode; //前置节点为空 if (pred == null) //说明插入到了首位 first = newNode; else //把前置节点的next指针也指向新建的节点 pred.next = newNode; size++; modCount++; }
//删除首位的元素,元素必须非空 private E unlinkFirst(Node<E> f){ // assert f == first && f != null; final E element = 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; }
//引用了node方法,需要遍历 public E set(int index, E element){ checkElementIndex(index); Node<E> x = node(index); E oldVal = x.item; x.item = element; return oldVal; }
//也可能需要遍历 publicvoidadd(int index, E element){ checkPositionIndex(index);
if (index == size) linkLast(element); else linkBefore(element, node(index)); }
//也要遍历 public E remove(int index){ checkElementIndex(index); return unlink(node(index)); }
public E peek(){ final Node<E> f = first; return (f == null) ? null : f.item; }
public E element(){ return getFirst(); }
public E poll(){ final Node<E> f = first; return (f == null) ? null : unlinkFirst(f); }