LinkedList
以双向链表实现。链表无容量限制,但双向链表本身使用了更多空间,每插入一个元素都要构造一个额外的Node对象,也需要额外的链表指针操作。按下标访问元素-get(i)、set(i,e)要悲剧的部分遍历链表将指针移动到位(如果i>数组大小的一半,会从末尾移起)。插入、删除元素时修改前后节点的指针即可,不再需要复制移动。但还是要部分遍历链表的指针才能移动到下标所指的位置。只有在链表两头的操作-add()、addFirst()、removeLast()或用iterator()上的remove()倒能省掉指针的移动。
// Node为LinkedList的内部类,它定义了存储的元素,上一个元素,下一个元素,这是典型的双向链表的定义方式。
private static class Node {
E item;
Node next;
Node prev;
Node(Node prev, E element, Node next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}
构造方法
LinkedList提供了两个构造方法:
LinkedList():构造一个空的LinkedList
LinkedList(Collection extends E> c):构造一个包含指定元素的LinkedList
add()
public boolean add(E e) {
linkLast(e);
return true;
}
void linkLast(E e) {
final Node l = last;
// 构造一个新的新节点
final Node newNode = new Node<>(l, e, null);
last = newNode;
// 如果链表是空的,第一个元素就是新建的,如果不是空的,将引用指向新建的节点
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
modCount++; // 容量修改次数分别+1
}
调用add()方法,将元素追加到链表末尾。除了add()方法,还提供了其他add方法
addFirst(E e):插入新元素到链表头部
addLast(E e):插入新元素到链表尾部
addAll(Collection extends E> c):插入新的集合
addAll(int index, Collection extends E> c):在指定位置插入新的集合
remove()
// 移除链表中遇到的第一个指定元素,如果列表中不包含,不做任何操作
public boolean remove(Object o) {
if (o == null) {
for (Node x = first; x != null; x = x.next) {
if (x.item == null) {
unlink(x);
return true;
}
}
} else {
for (Node x = first; x != null; x = x.next) {
if (o.equals(x.item)) {
unlink(x);
return true;
}
}
}
return false;
}
set()
// 替换指定位置的元素
public E set(int index, E element) {
checkElementIndex(index);
Node x = node(index);
E oldVal = x.item;
x.item = element;
return oldVal;
}
get()
// 返回指定位置的元素
public E get(int index) {
checkElementIndex(index);
return node(index).item;
}