Java集合(JDK8) LinkedList篇
首先先看看LinkedList的继承关系
1、添加一个元素
/**
* Appends the specified element to the end of this list.
*
* <p>This method is equivalent to {@link #addLast}.
*
* @param e element to be appended to this list
* @return {@code true} (as specified by {@link Collection#add})
*/
public boolean add(E e) {
//默认是将元素添加到链表的尾部,作为尾结点
linkLast(e);
return true;
}
/**
* Links e as last element.
*/
void linkLast(E e) {
//记录下当前的尾结点
final Node<E> l = last;
//创建一个结点,数据为e,前驱结点为l,后继结点为null
final Node<E> newNode = new Node<>(l, e, null);
//将新插入的结点作为尾结点
last = newNode;
//如果该结点是第一个结点,则作为首结点
if (l == null)
first = newNode;
//否则作为l的后继结点
else
l.next = newNode;
size++;
//记录下链表结构改变
modCount++;
}
2、在指定的位置插入元素
public void add(int index, E element) {
//判断index是否合法
checkPositionIndex(index);
//如果index刚好等于链表的长度,则将该结点作为尾结点
if (index == size)
linkLast(element);
else
linkBefore(element, node(index));
}
/**
* Returns the (non-null) Node at the specified element index.
* 找到第index结点
*/
Node<E> node(int index) {
// assert isElementIndex(index);
//如果index是在前半部分,则从头结点往后遍历
if (index < (size >> 1)) {
Node<E> x = first;
for (int i = 0; i < index; i++)
x = x.next;
return x;
} else {
//如果index是在后半部分,则从尾结点往前遍历
Node<E> x = last;
for (int i = size - 1; i > index; i--)
x = x.prev;
return x;
}
}
/**
* Inserts element e before non-null Node succ.
* 将结点e插入到succ结点之前
*/
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++;
}