LinkedList
LinkedList 底层使用双向链表存储,对于频繁的插入、删除操作,效率较高。在get与set方面弱于ArrayList. 适用于 :没有大规模的随机读取,有大量的增加/删除操作.随机访问很慢,增删操作很快,不耗费多余资源 ,允许null元素,非线程安全。
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
transient int size = 0;
transient Node<E> first;
transient Node<E> last;
}
LinkedList 继承自 AbstractSequentialList 类,实现了 List 、 Deque 、 Cloneable 、 Serializable 接口。
transient 关键字表示不可被序列化。
size 表示链表中存储元素的个数。
first 为指向第一个节点的指针。
last 为只想最后一个节点的指针。
Node
Node 是用于保存节点数据的类,包含一个 item 属性用于存储当前节点的值, next 表示指向下一个节点的指针, prev 表示指向前一个节点的指针。
private static class Node<E> {
E item;
Node<E> next;
Node<E> prev;
Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}
Linkedlist()
创建一个空的链表。
public LinkedList() {
}
LinkedList(Collection<? extends E>)
创建一个链表,包含集合 c 中的所有元素。
- 先调用空构造器创建一个空链表,然后调用 addAll() 方法将集合 c 中的元素都添加到当前链表中。
public LinkedList(Collection<? extends E> c) {
this();
addAll(c);
}
addAll(Collection<? extends E>)
将集合中 c 的元素全部添加到当前链表结尾。
public boolean addAll(Collection<? extends E> c) {
return addAll(size, c);
}
addAll(int, Collection<? extends E>)
将集合 c 中的元素添加到当前链表指定位置之后
- 初始化 pred 指向索引 index - 1 节点,succ 为索引 index 处的节点。
- 每次将一个节点添加到pred之后,然后更新当前节点为pred节点。
- 最后将 pred 的下一个节点指向 succ ,succ 的前一个节点指向 pred 。
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; //pred指向索引 index - 1 节点,succ为索引 index 处的节点
if (index == size) {
succ = null;
pred = last;
} else {
succ = node(index);
pred = succ.prev;
}
for (Object o : a) { //每次将一个节点添加到pred之后,然后更新当前节点为pred节点。
@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) { //最后将 pred 的下一个节点指向 succ ,succ 的前一个节点指向 pred 。
last = pred;
} else {
pred.next = succ;
succ.prev = pred;
}
size += numNew;
modCount++;
return true;
}
linkFirst(E)
将元素 e 添加到链表的头部,即头插法。
- 创建一个 prev (前节点)指向空, next (后节点)指向 first (头节点)的节点,同时将当前头节点 f 的的 prev 指向新节点 newNode 。
- 将头节点指向新节点 newNode ,更新 size 大小。
private void linkFirst(E e) {
final Node<E> f = first;
final Node<E> newNode = new Node<>(null, e, f);
first = newNode;
if (f == null)
last = newNode;
else
f.prev = newNode;
size++;
modCount++;
}
linkLast(E)
将元素 e 添加到链表的尾部,即尾插法。
- 创建一个 prev (前节点)指向 last (尾节点), next (后节点)指向空的节点,同时将当前尾节点 l 的的 next 指向新节点 newNode 。
- 将尾节点指向新节点 newNode ,更新 size 大小。
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++;
}
linkBefore(E, Node<E>)
将元素 e 插入到非空节点 succ 之前。
- 创建一个 prev (前节点)指向 succ 的前节点, next (后节点)指向 succ 节点,同时将 succ 的 prev (前节点)指向新节点 newNode 。
- 将 pred 的下一个节点指向新节点 newNode ,更新 size 大小。
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++;
}
unlinkFirst(Node<E>)
将头节点从链表中删除,并返回头节点元素的值。
- 获取头节点元素的值 element ,头节点的下一个节点 next 。
- 将头节点置为 null ,将节点 next 设为头节点 first ,将 next 节点的 prev (前节点)置为 null 。因为头节点的前节点为空。
- 更新 size 大小,返回刚才的头节点元素值 element 。
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;
}
unlinkLast(Node<E>)
将尾节点从链表中删除,并返回尾节点元素的值。
- 获取尾节点元素的值 element ,尾节点的前一个节点 prev 。
- 将尾节点置为 null ,将节点 prev 设为尾节点 last ,将 prev 节点的 next (后节点)置为 null 。因为尾节点的后节点为空。
- 更新 size 大小,返回刚才的尾节点元素值 element 。
private E unlinkLast(Node<E> l) {
// assert l == last && l != null;
final E element = l.item;
final Node<E> prev = l.prev;
l.item = null;
l.prev = null; // help GC
last = prev;
if (prev == null)
first = null;
else
prev.next = null;
size--;
modCount++;
return element;
}
unlink(Node<E>)
将指定的节点从链表中删除,并返回该节点的值。
- 获取指定节点 x 的值 element ,节点 x 的下一节点 next ,和前一个节点 prev 。
- 将 prev 节点的下一个节点指向 next ,将 next 节点的前一个节点指向 prev 。将 x 节点的前一个和后一个节点置为 null 。即将该节点从链表中删除。
- 更新 size 大小,返回 x 节点的值 element 。
E unlink(Node<E> x) {
// assert x != null;
final E element = x.item;
final Node<E> next = x.next;
final Node<E> prev = x.prev;
if (prev == null) {
first = next;
} else {
prev.next = next;
x.prev = null;
}
if (next == null) {
last = prev;
} else {
next.prev = prev;
x.next = null;
}
x.item = null;
size--;
modCount++;
return element;
}
getFirst()
返回头节点的值。
public E getFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return f.item;
}
getLast()
返回尾节点的值。
public E getLast() {
final Node<E> l = last;
if (l == null)
throw new NoSuchElementException();
return l.item;
}
removeFirst()
删除头节点,调用 unlinkFirst() 方法实现。
public E removeFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return unlinkFirst(f);
}
removeLast()
删除尾节点,调用 unlinkLast() 方法实现。
public E removeLast() {
final Node<E> l = last;
if (l == null)
throw new NoSuchElementException();
return unlinkLast(l);
}
addFirst(E)
将指定元素 e 添加到链表头部(头插法),调用 linkFirst() 方法实现。
public void addFirst(E e) {
linkFirst(e);
}
addLast(E)
将指定元素 e 添加到链表结尾(尾插法),调用 linkLast() 方法实现。
public void addLast(E e) {
linkLast(e);
}
contains(Object)
判断链表中是否包含指定的值 o ,调用 indexOf(Object) 方法实现,即查找该元素在链表中的位置,如果大于等于零,表示链表中包含该元素。
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
indexOf(Object)
返回指定元素在链表中的位置,如果链表中不包含该元素则返回 -1 。
- 从头节点开始遍历整个链表,每遍历一个节点,index 加1,直到当前节点的值等于指定对象 o ,返回 index 的大小。
- 如果遍历到尾节点仍未找到与 o 值相等的节点,则返回 -1 。( index 从 0 开始)
public int indexOf(Object o) {
int index = 0;
if (o == null) {
for (Node<E> x = first; x != null; x = x.next) {
if (x.item == null)
return index;
index++;
}
} else {
for (Node<E> x = first; x != null; x = x.next) {
if (o.equals(x.item))
return index;
index++;
}
}
return -1;
}
lastIndexOf(Object)
返回指定元素在链表中的最后一个位置,如果链表中不包含该元素则返回 -1 。
- 初始化 index 大小为 size 。从尾节点开始遍历整个链表,每遍历一个节点,index 减1,直到当前节点的值等于指定对象 o ,返回 index 的大小。
- 如果遍历到头节点仍未找到与 o 值相等的节点,则返回 -1 。( index 从 0 开始)
public int lastIndexOf(Object o) {
int index = size;
if (o == null) {
for (Node<E> x = last; x != null; x = x.prev) {
index--;
if (x.item == null)
return index;
}
} else {
for (Node<E> x = last; x != null; x = x.prev) {
index--;
if (o.equals(x.item))
return index;
}
}
return -1;
}
size()
返回当前链表中节点的数量。
public int size() {
return size;
}
add(E)
将指定元素 e 添加到当前链表的末尾,调用 linkLast() 方法实现。
public boolean add(E e) {
linkLast(e);
return true;
}
remove(Object)
从当前链表中删除指定的第一个元素 e 。
- 和 indexOf(Object) 方法类似,从头节点开始遍历链表,找到当前节点值等于指定对象 o 的节点,然后调用 unlink(Node<E>) 方法删除该节点。
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;
}
clear()
删除当前链表中的所有节点。
- 从头节点开始遍历,将每个节点都置为 null ,即删除了该链表中的每个节点。
public void clear() {
// Clearing all of the links between nodes is "unnecessary", but:
// - helps a generational GC if the discarded nodes inhabit
// more than one generation
// - is sure to free memory even if there is a reachable Iterator
for (Node<E> x = first; x != null; ) {
Node<E> next = x.next;
x.item = null;
x.next = null;
x.prev = null;
x = next;
}
first = last = null;
size = 0;
modCount++;
}
get(int)
返回当前链表中的第 index (从 0 开始)个节点的值,通过调用 node(int) 方法获得当前链表第 index 个节点,然后返回该节点的 item 属性,即该节点的值。
public E get(int index) {
checkElementIndex(index); //检查 index 是否合法,即 0 <= index < size
return node(index).item;
}
node(int)
返回当前链表中的第 index 个节点。( index 从 0 开始)
- 如果 index 的值小于二分之 size ,则从头节点往后遍历,直到第 index 个节点。
- 如果 index 的值大于二分之 size ,则从尾节点往前遍历,直到第 index 个节点。
Node<E> node(int index) {
// assert isElementIndex(index);
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;
}
}
set(int, E)
将当前链表第 index 个节点的值设为 element ,返回该节点原来的值 oldValue 。( index 从 0 开始)
- 调用 node(int) 方法获得当前链表第 index 个节点 x ,然后获取 x 节点的值 oldValue 。
- 将 x 节点的值更改为 element ,返回 oldValue 。
public E set(int index, E element) {
checkElementIndex(index); //检查 index 是否合法,即 0 <= index < size
Node<E> x = node(index);
E oldVal = x.item;
x.item = element;
return oldVal;
}
add(int, E)
将元素 element 添加到当前链表的第 index 个位置。( index 从 0 开始)
- 如果 index 等于 size ,即将该元素插入到末尾,调用 linkLast(E) 方法将元素 element 插入到链表末尾。
- 否则,调用 linkBefore(E, Node<E>) 方法将元素 element 插入到当前链表的第 index 个位置。
public void add(int index, E element) {
checkPositionIndex(index); //检查 index 是否合法,即 0 <= index <= size
if (index == size)
linkLast(element);
else
linkBefore(element, node(index));
}
remove(int)
删除当前链表的第 index (从 0 开始)节点,先使用 node(int) 方法获取当前链表的第 index 个节点,然后调用 unlink(Node<E>) 方法将该节点从链表中删除。
public E remove(int index) {
checkElementIndex(index); //检查 index 是否合法,即 0 <= index < size
return unlink(node(index));
}
listIterator(int)
返回当前链表的迭代器对象,且该迭代器对象指向链表中第 index 个节点,调用 ListItr 类的构造方法实现。( index 从 0 开始)
public ListIterator<E> listIterator(int index) {
checkPositionIndex(index);
return new ListItr(index);
}
ListItr(int index) {
// assert isPositionIndex(index);
next = (index == size) ? null : node(index);
nextIndex = index;
}
descendingIterator()
返回当前链表的迭代器对象,且该迭代器对象指向链表的末尾(并非尾节点),该迭代器从尾节点往头节点方向进行遍历。
public Iterator<E> descendingIterator() {
return new DescendingIterator();
}
private class DescendingIterator implements Iterator<E> {
private final ListItr itr = new ListItr(size());
public boolean hasNext() {
return itr.hasPrevious();
}
public E next() {
return itr.previous();
}
public void remove() {
itr.remove();
}
}
clone()
将当前链表克隆并返回。
- 调用父类 AbstractSequentialList 类的克隆方法。
- 将当前链表的节点都添加到克隆对象中。只是值的拷贝,两个对象的节点地址并不相同。
public Object clone() {
LinkedList<E> clone = superClone(); //调用父类 AbstractSequentialList 类的克隆方法
// Put clone into "virgin" state
clone.first = clone.last = null;
clone.size = 0;
clone.modCount = 0;
// Initialize clone with our elements
for (Node<E> x = first; x != null; x = x.next) //将当前链表的节点都添加到克隆对象中。只是值的拷贝,两个对象的节点地址并不相同。
clone.add(x.item);
return clone;
}
toArray()
将当前链表以数组的形式返回。
- 创建一个大小为 size 的数组,从头节点开始遍历当前链表,将每个节点的值逐个添加到数组中,返回数组 result 。
public Object[] toArray() {
Object[] result = new Object[size];
int i = 0;
for (Node<E> x = first; x != null; x = x.next)
result[i++] = x.item;
return result;
}
toArray(T[])
将当前链表的值保存到指定类型数组 a 中并返回。
- 如果数组 a 的长度小于链表的长度 size ,创建一个长度为 size 的数组赋给 a 。
- 从头节点开始遍历当前链表,将每个节点的值逐个添加到数组中,返回数组 a 。
public <T> T[] toArray(T[] a) {
if (a.length < size)
a = (T[])java.lang.reflect.Array.newInstance(
a.getClass().getComponentType(), size);
int i = 0;
Object[] result = a;
for (Node<E> x = first; x != null; x = x.next)
result[i++] = x.item;
if (a.length > size)
a[size] = null;
return a;
}
writeObject(ObjectOutputStream)
将当前列表的内容(长度和元素)写入到输出流中。
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
// Write out any hidden serialization magic
s.defaultWriteObject();
// Write out size
s.writeInt(size);
// Write out all elements in the proper order.
for (Node<E> x = first; x != null; x = x.next)
s.writeObject(x.item);
}
readObject(ObjectInputStream)
从输入流中读取列表的内容(长度和元素),保存到当前列表中。
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
// Read in any hidden serialization magic
s.defaultReadObject();
// Read in size
int size = s.readInt();
// Read in all elements in the proper order.
for (int i = 0; i < size; i++)
linkLast((E)s.readObject());
}
spliterator()
在此集合中的元素上创建一个spliterator,用来遍历和划分集合元素。可用于并行遍历。
public Spliterator<E> spliterator() {
return new LLSpliterator<>(this, -1, 0);
}
关于队列 Deque 接口的方法
peek()
返回当前队列(链表)的头节点的值,当头节点为空时,返回 null 。
public E peek() {
final Node<E> f = first;
return (f == null) ? null : f.item;
}
element()
返回当前队列(链表)的头节点的值,当头节点为空时,抛出异常, 调用 getFirst() 方法实现。
public E element() {
return getFirst();
}
poll()
将队列(链表)的头节点删除,并返回该节点的值,调用 unlinkFirst(Node<E>) 方法实现。
public E poll() {
final Node<E> f = first;
return (f == null) ? null : unlinkFirst(f);
}
remove()
将队列(链表)的头节点删除,并返回该节点的值,调用 removeFirst(Node<E>) 方法实现, 如果头节点为空,抛出异常。
public E remove() {
return removeFirst();
}
offer(E)
将给定元素添加到队列(链表)的末尾,调用 add(E) 方法实现。
public boolean offer(E e) {
return add(e);
}
offerFirst(E)
将给定元素添加到当前队列(链表)的头部,调用 addFirst(E) 方法实现。
public boolean offerFirst(E e) {
addFirst(e);
return true;
}
offerLast(E)
将给定元素添加到当前队列(链表)的尾部,调用 addLast(E) 方法实现。
public boolean offerLast(E e) {
addLast(e);
return true;
}
peekFirst()
返回当前队列(链表)的头节点的值,当头节点为空时,返回 null 。
public E peekFirst() {
final Node<E> f = first;
return (f == null) ? null : f.item;
}
peekLast()
返回当前队列(链表)的尾节点的值,当尾节点为空时,返回 null 。
public E peekLast() {
final Node<E> l = last;
return (l == null) ? null : l.item;
}
pollFirst()
将队列(链表)的头节点删除,并返回该节点的值,调用 unlinkFirst(Node<E>) 方法实现。
public E pollFirst() {
final Node<E> f = first;
return (f == null) ? null : unlinkFirst(f);
}
pollLast()
将队列(链表)的尾节点删除,并返回该节点的值,调用 unlinkLast(Node<E>) 方法实现。
public E pollLast() {
final Node<E> l = last;
return (l == null) ? null : unlinkLast(l);
}
push(E)
将给定元素添加到栈(链表)的头部,调用 addFirst(E) 方法实现。
public void push(E e) {
addFirst(e);
}
pop()
将当前栈顶(链表头节点)删除,调用 removeFirst() 方法实现。
public E pop() {
return removeFirst();
}
removeFirstOccurrence(Object)
删除当前链表中的第一个值为 o 的节点,调用 remove(Object) 方法实现。
public boolean removeFirstOccurrence(Object o) {
return remove(o);
}
removeLastOccurrence(Object)
删除当前链表中的最后一个值为 o 的节点。
- 从链表的尾节点开始往前遍历,直到找到值和 o 相等的节点,调用 unlink(Node<E>) 方法删除该节点。
public boolean removeLastOccurrence(Object o) {
if (o == null) {
for (Node<E> x = last; x != null; x = x.prev) {
if (x.item == null) {
unlink(x);
return true;
}
}
} else {
for (Node<E> x = last; x != null; x = x.prev) {
if (o.equals(x.item)) {
unlink(x);
return true;
}
}
}
return false;
}
descendingIterator()
返回当前队列(链表)的迭代器对象,且该迭代器对象指向链表的末尾(并非尾节点),该迭代器从尾节点往头节点方向进行遍历。
public Iterator<E> descendingIterator() {
return new DescendingIterator();
}
private class DescendingIterator implements Iterator<E> {
private final ListItr itr = new ListItr(size());
public boolean hasNext() {
return itr.hasPrevious();
}
public E next() {
return itr.previous();
}
public void remove() {
itr.remove();
}
}