/** * 根据指定集合创建链表 * @param c the collection whose elements are to be placed into this list * @throws NullPointerException if the specified collection is null */ public LinkedList(Collection<? extends E> c) { this(); addAll(c); }
add方法
1 2 3 4
public boolean add(E e) { linkLast(e);//插入链表尾部 return true; }
1 2 3 4 5 6 7 8 9 10 11
void linkLast(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++; }
在指定位置插入的add方法
1 2 3 4 5 6 7
public void add(int index, E element) { checkPositionIndex(index);//检查下标范围 if (index == size)//判断下标值 linkLast(element);//插入尾部(上面讲过了) else linkBefore(element, node(index));//插入指定位置 }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Node<E> node(int index) { // assert isElementIndex(index); //判断下标是否小于链表大小/2 //这里对半查询 //size>>1==size/2 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; } }
1 2 3 4 5 6 7 8 9 10 11 12 13
void linkBefore(E e, Node<E> succ) { // assert succ != null; final Node<E> pred = succ.prev;获得原位置节点的前驱节点 final Node<E> newNode = new Node<>(pred, e, succ);//创建新节点 succ.prev = newNode;原位置节点的前驱节点指向新节点 if (pred == null)//判断是否为头节点 first = newNode;头节点指向新节点 else pred.next = newNode; size++; modCount++; }
addAll方法
1 2 3
public boolean addAll(Collection<? extends E> c) { return addAll(size, c);//尾部批量插入 }
public boolean addAll(int index, Collection<? extends E> c) { checkPositionIndex(index);//检测下标范围
Object[] a = c.toArray();//集合转换为数组 int numNew = a.length; if (numNew == 0) return false;
Node<E> pred, succ; if (index == size){//判断下标长度是否等于链表长度,即插入尾部 succ = null; pred = last; } else { succ = node(index); pred = succ.prev; } //循环遍历指定数组 for (Object o : a) { @SuppressWarnings("unchecked") E e = (E) o; Node<E> newNode = new Node<>(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++; return true; }
remove方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
//删除指定元素 public boolean remove(Object o) { if (o == null) { for (Node<E> x = first; x != null; x = x.next) { if (x.item == null) { unlink(x); return true; } } } else { for (Node<E> x = first; x != null; x = x.next) { if (o.equals(x.item)) { unlink(x); return true; } } } return false; }