[Java] 纯文本查看 复制代码
public class LinkedList<E>extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable {
transient int size = 0; //LinkedList中存放的元素个数
transient Node<E> first; //头节点
transient Node<E> last; //尾节点
//构造方法,创建一个空的列表
public LinkedList() {
}
//将一个指定的集合添加到LinkedList中,先完成初始化,在调用添加操作
public LinkedList(Collection<? extends E> c) {
this();
addAll(c);
}
//插入头节点
private void linkFirst(E e) {
final Node<E> f = first; //将头节点赋值给f节点
//new 一个新的节点,此节点的data = e , pre = null , next - > f
final Node<E> newNode = new Node<>(null, e, f);
first = newNode; //将新创建的节点地址复制给first
if (f == null) //f == null,表示此时LinkedList为空
last = newNode; //将新创建的节点赋值给last
else
f.prev = newNode; //否则f.前驱指向newNode
size++;
modCount++;
}
//插入尾节点
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++;
}
}