LinkedList 底层是一个双向链表。是一个直线型的链表结构。
LinkedList 特点:查询慢,增删快。
LinkedList继承于AbstractSequentialList 实现了List、Deque、Cloneable、java.io.Serializable这些接口。如下:
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable
LinkedList 定义了一个私有内部类Node,用来表示链表数据结构,也就是通过Node来存储元素。
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;
}
}
//集合大小
transient int size = 0;
/**
* Pointer to first node.
* - 头节点
* Invariant: (first == null && last == null) ||
* (first.prev == null && first.item != null)
* - 固定式:1.头节点为空,尾节点必然为空;2.头节点中上一个节点为空,元素不为空
*/
transient Node<E> first;
/**
* Pointer to last node.
* - 尾节点
* Invariant: (first == null && last == null) ||
* (last.next == null && last.item != null)
* - 固定式:1.头节点为空,尾节点必然为空;2.尾节点中下一个节点为空,元素不为空
*/
transient Node<E> last;
无参构造:构造一个空列表。
/**
* Constructs an empty list.
* - 构造一个空列表。
*/
public LinkedList() {
}
构造一个包含指定 collection 的元素的列表,这些元素是按照该 collection 的迭代器返回它们的顺序排列的。
/**
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
* - 构造一个包含指定 collection 的元素的列表,这些元素是按照该 collection 的迭代器返回它们的顺序排列的。
*
* @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);
}
/**
* Appends all of the elements in the specified collection to the end of
* this list, in the order that they are returned by the specified
* collection's iterator. The behavior of this operation is undefined if
* the specified collection is modified while the operation is in
* progress. (Note that this will occur if the specified collection is
* this list, and it's nonempty.)
* - 将指定集合中的所有元素按照该 collection 的迭代器返回它们的顺序追加到此列表的末尾。如果在操作过程中修改了指定的集合,则此操作的行为未定义。(注意,如果指定的集合是这个列表,并且它不是空的,则会发生这种情况。)
*
* @param c collection containing elements to be added to this list
* @return {@code true} if this list changed as a result of the call
* @throws NullPointerException if the specified collection is null
*/
public boolean addAll(Collection<? extends E> c) {
return addAll(size, c);
}
/**
* Inserts all of the elements in the specified collection into this
* list, starting at the specified position. Shifts the element
* currently at that position (if any) and any subsequent elements to
* the right (increases their indices). The new elements will appear
* in the list in the order that they are returned by the
* specified collection's iterator.
* - 从指定位置开始,将指定集合中的所有元素插入此列表。将当前位于该位置的元素(如果有)和任何后续元素向右移动(增加它们的索引)。新元素将按照指定集合的迭代器返回它们的顺序出现在列表中。
*
* @param index index at which to insert the first element
* from the specified collection
* @param c collection containing elements to be added to this list
* @return {@code true} if this list changed as a result of the call
* @throws IndexOutOfBoundsException {@inheritDoc}
* @throws NullPointerException if the specified collection is null
*/
public boolean addAll(int index, Collection<? extends E> c) {
// 检查索引是否月结
checkPositionIndex(index);
// 集合转换数组
Object[] a = c.toArray();
int numNew = a.length;
// 集合长度为空,直接返回
if (numNew == 0)
return false;
// pred:指代待添加节点的前一个节点。
// succ:指代添加节点的位置。
Node<E> pred, succ;
// index == size:待添加的元素永远在最后
// index != size:先获取指定索引对应的Node节点,在把Node节点赋值给Pred
if (index == size) {
succ = null;
pred = last;
} else {
// node(index):获取指定索引对应的Node节点
succ = node(index);
pred = succ.prev;
}
for (Object o : a) {
// @SuppressWarnings("unchecked")
// 告诉编译器忽略 unchecked 警告信息
@SuppressWarnings("unchecked") E e = (E) o;
Node<E> newNode = new Node<>(pred, e, null);
// pred == null:头节点
// pred != null:非头节点,上一个节点,指向下一个节点
if (pred == null)
first = newNode;
else
pred.next = newNode;
pred = newNode;
}
// succ == null:表示新添加的元素,是最后一个元素。
// succ != null:新添加的元素不是最后一个元素。
if (succ == null) {
last = pred;
} else {
pred.next = succ;
succ.prev = pred;
}
// 更新长度
size += numNew;
// 修改的次数
modCount++;
return true;
}
/**
* - 检查索引是否越界
*/
private void checkPositionIndex(int index) {
if (!isPositionIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
/**
* Tells if the argument is the index of a valid position for an
* iterator or an add operation.
* - 检查索引是否越界
*/
private boolean isPositionIndex(int index) {
return index >= 0 && index <= size;
}
/**
* Returns the (non-null) Node at the specified element 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;
}
}
设置头节点元素
/**
* Links e as first element.
* - 设置头节点元素
*/
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++;
}
总结:新建节点赋值给头节点,判断旧头节点是否为空,若为空赋值给尾节点;若不为空把旧头节点的上一个节点指向头节点。
将该元素插入此列表的头部。
/**
* Inserts the specified element at the beginning of this list.
*
* @param e the element to add
*/
public void addFirst(E e) {
linkFirst(e);
}
总结:内部调用linkFirst()。
设置尾节点元素
/**
* Links e as last element.
* - 设置为节点元素
*/
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++;
}
总结:新建节点赋值给尾节点,判断旧尾节点是否为空,若为空表示该集合为空,没有头节点;若不为空把旧尾节点的下一个节点指向尾节点。
将该元素插入到此列表的末尾。
/**
* Appends the specified element to the end of this list.
*
* <p>This method is equivalent to {@link #add}.
*
* @param e the element to add
*/
public void addLast(E e) {
linkLast(e);
}
总结:内部调用linkLast()。
在非空节点之前插入元素e。
/**
* Inserts element e before non-null Node succ.
* - 在非空节点之前插入元素e。
*/
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++;
}
总结:新建一个节点元素,将上一个节点指向当前节点,将当前旧节点指向新节点。
删除头节点,并且返回删除的节点的值,使用该方法的前提是参数f是头节点,而且f不能为空。
/**
* Unlinks non-null first node f.
* - 删除头节点
*/
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;
}
总结:头节点置空,把下一节点设置为头节点,若下一节点为空,则尾节点为空。
删除头节点,并且返回删除的节点的值。
/**
* Removes and returns the first element from this list.
* - 删除头节点,并且返回删除的节点的值。
* @return the first element from this list
* @throws NoSuchElementException if this list is empty
*/
public E removeFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return unlinkFirst(f);
}
总结:该方法内部调用unlinkFirst()。
删除尾节点,并且返回删除节点的值。
/**
* Unlinks non-null last node l.
* - 删除尾节点,并且返回尾节点的值。
*/
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;
}
总结:尾节点置空,把上一节点设置为尾节点,若上一节点为空,则头节点为空。
删除指定节点,该节点不为空。
/**
* Removes and returns the last element from this list.
* - 删除指定节点,该节点不为空。
* @return the last element from this list
* @throws NoSuchElementException if this list is empty
*/
public E removeLast() {
final Node<E> l = last;
if (l == null)
throw new NoSuchElementException();
return unlinkLast(l);
}
总结:该方法内部调用unlinkLast()。
删除指定节点,该节点不为空。
/**
* Unlinks non-null node x.
* - 删除指定节点,该节点不为空。
*/
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;
}
总结:将该节点置空,需要判断是头节点还是尾节点。
获取头节点元素。
/**
* Returns the first element in this list.
* - 返回头节点元素。
* @return the first element in this list
* @throws NoSuchElementException if this list is empty
*/
public E getFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return f.item;
}
总结:若头节点为空,抛出NoSuchElementException。
获取尾节点元素。
/**
* Returns the last element in this list.
*
* @return the last element in this list
* @throws NoSuchElementException if this list is empty
*/
public E getLast() {
final Node<E> l = last;
if (l == null)
throw new NoSuchElementException();
return l.item;
}
总结:若尾节点为空,抛出NoSuchElementException。
判断是否包含某一个元素。
/**
* Returns {@code true} if this list contains the specified element.
* More formally, returns {@code true} if and only if this list contains
* at least one element {@code e} such that
* <tt>(o==null ? e==null : o.equals(e))</tt>.
* - 如果此列表包含指定的元素,则返回true。
* @param o element whose presence in this list is to be tested
* @return {@code true} if this list contains the specified element
*/
public boolean contains(Object o) {
return indexOf(o) != -1;
}
/**
* Returns the index of the first occurrence of the specified element
* in this list, or -1 if this list does not contain the element.
* More formally, returns the lowest index {@code i} such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
* or -1 if there is no such index.
* - 返回该列表中指定元素第一次出现的索引,如果该列表不包含该元素,则返回-1。
* @param o element to search for
* @return the index of the first occurrence of the specified element in
* this list, or -1 if this list does not contain the element
*/
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;
}
总结:循环遍历每个节点,判断是否存在,若存在则返回ture。
获取指定元素最后一次出现的索引,如果此列表不包含该元素,则返回-1。
/**
* Returns the index of the last occurrence of the specified element
* in this list, or -1 if this list does not contain the element.
* More formally, returns the highest index {@code i} such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
* or -1 if there is no such index.
* - 获取指定元素最后一次出现的索引,如果此列表不包含该元素,则返回-1。
* @param o element to search for
* @return the index of the last occurrence of the specified element in
* this list, or -1 if this list does not contain the element
*/
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;
}
总结:循环遍历链表,判断元素是否存在。
检索头节点,但不删除头节点。返回头节点元素。
/**
* Retrieves, but does not remove, the head (first element) of this list.
* - 检索头节点,但不删除头节点。
* @return the head of this list, or {@code null} if this list is empty
* @since 1.5
*/
public E peek() {
final Node<E> f = first;
return (f == null) ? null : f.item;
}
其他方法不做阐述,看到这里再看其他方法基本都能看懂。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有