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;
}
}
public class LinkedList
extends AbstractSequentialList
implements List, Deque, Cloneable, java.io.Serializable
// 不可序列化
transient int size = 0;
transient Node first;
transient Node last;
protected transient int modCount = 0;
public LinkedList() {}
public LinkedList(Collection extends E> c) {
this();
addAll(c); // 调用addAll()方法,把传入的c复制给该LinkedList,addAll()具体实现后面讲
}
public E getFirst() {
final Node f = first;
if (f == null)
throw new NoSuchElementException();
return f.item;
}
public E getLast() {
final Node l = last;
if (l == null)
throw new NoSuchElementException();
return l.item;
}
public E removeFirst() {
final Node f = first;
if (f == null)
throw new NoSuchElementException();
return unlinkFirst(f); // 调用unlinkFirst(Node f)来移除首元素
}
private E unlinkFirst(Node f) {
final E element = f.item;
final Node 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;
}
public E removeLast() {
final Node l = last;
if (l == null)
throw new NoSuchElementException();
return unlinkLast(l);
}
private E unlinkLast(Node l) {
final E element = l.item;
final Node 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;
}
public void addFirst(E e) {
linkFirst(e);
}
private void linkFirst(E e) {
final Node f = first; // 拿到首元素
final Node newNode = new Node<>(null, e, f); // 根据传入的值新建一个结点
first = newNode; // 将头指针指向新建的结点
if (f == null) // 如果列表本来为空
last = newNode; // 则尾元素也是新建的元素
else // 否则
f.prev = newNode; // 原首元素的前指针指向新的首元素
size++;
modCount++;
}
public void addLast(E e) {
linkLast(e);
}
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++;
}
public boolean contains(Object o) {
return indexOf(o) != -1;
}
public int indexOf(Object o) {
int index = 0;
if (o == null) { // 判断是否包含元素值为null的元素
for (Node x = first; x != null; x = x.next) {
if (x.item == null)
return index;
index++;
}
} else { // 通过equals方法判断是否包含该不为null的元素,不能通过值比较,而是通过对象是否equals来比较
for (Node x = first; x != null; x = x.next) {
if (o.equals(x.item))
return index;
index++;
}
}
return -1;
}
public int indexOf(Object o) {
int index = 0;
if (o == null) { // 判断是否包含元素值为null的元素
for (Node x = first; x != null; x = x.next) {
if (x.item == null)
return index;
index++;
}
} else { // 通过equals方法判断是否包含该不为null的元素,不能通过值比较,而是通过对象是否equals来比较
for (Node x = first; x != null; x = x.next) {
if (o.equals(x.item))
return index;
index++;
}
}
return -1;
}
public int size() {
return size;
}
public boolean add(E e) {
linkLast(e);
return true;
}
(10) remove(Object o):移除元素
源码解释:
首先通过查找是否包含该元素,实现原理和contains方法一致,在找到的时候,调用unlink方法,移除元素。
unlink方法就是将,要移除元素的前一个元素的后指针指向移除元素的下一个元素,要移除元素的下一个元素的前指针指向要移除元素的上一个元素,当然,要判断前后元素是否为空的状态。
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;
}
E unlink(Node x) {
final E element = x.item;
final Node next = x.next;
final Node 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; // 移除元素置空,等待gc
size--;
modCount++;
return element;
}
public boolean addAll(Collection extends E> c) {
return addAll(size, c);
}
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 pred, succ; // pred:中间变量, succ:插入位置的后一个元素
if (index == size) { // 如果插入位置为尾元素的下一个位置
succ = null; // 插入位置后面没有元素了
pred = last; // 新插入集合的前一个元素为原来的尾元素
} else { // 如果不是在尾部的下一个元素插入
succ = node(index); // 通过node()方法获取到index位置的元素
pred = succ.prev; // 插入集合的首元素的前指向为index位置的前一个元素
}
for (Object o : a) { // 循环遍历,使新插入集合元素的排列起来,并使pred指向新插入集合的最后一个元素
@SuppressWarnings("unchecked")
E e = (E) o;
Node newNode = new Node<>(pred, e, null);
if (pred == null)
first = newNode;
else
pred.next = newNode;
pred = newNode;
}
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));
}
private boolean isPositionIndex(int index) {
return index >= 0 && index <= size; // 判断index是否越界
}
public void clear() {
for (Node x = first; x != null;) {
Node next = x.next;
x.item = null;
x.next = null;
x.prev = null;
x = next;
}
first = last = null;
size = 0;
modCount++;
}
public E get(int index) {
checkElementIndex(index);
return node(index).item;
}
Node node(int index) {
if (index < (size >> 1)) { // size>>1,即size右移1位,即size / 2
Node x = first; // 从首结点向中间位置检索
for (int i = 0; i < index; i++)
x = x.next;
return x;
} else {
Node x = last; // 从尾结点向中间位置检索
for (int i = size - 1; i > index; i--)
x = x.prev;
return x;
}
}
public int indexOf(Object o) {
int index = 0;
if (o == null) {
for (Node x = first; x != null; x = x.next) {
if (x.item == null)
return index;
index++;
}
} else {
for (Node x = first; x != null; x = x.next) {
if (o.equals(x.item))
return index;
index++;
}
}
return -1;
}
public int lastIndexOf(Object o) {
int index = size;
if (o == null) {
for (Node x = last; x != null; x = x.prev) {
index--;
if (x.item == null)
return index;
}
} else {
for (Node x = last; x != null; x = x.prev) {
index--;
if (o.equals(x.item))
return index;
}
}
return -1;
}
public E peek() {
final Node f = first;
return (f == null) ? null : f.item;
}
(18) element():返回首元素
源码解释:
调用getFirst(),列表不存在抛出NoSuchElementExeption。
public E element() {
return getFirst();
}
public E poll() {
final Node f = first;
return (f == null) ? null : unlinkFirst(f);
}
(20) remove():移除首元素,并返回
源码解释:
调用unlinkFirst移除首元素,列表不存在抛出NoSuchElementExeption。
public E remove() {
return removeFirst();
}
public boolean offer(E e) {
return add(e);
}
public boolean add(E e) {
inkLast(e);
return true;
}
public boolean offerFirst(E e) {
addFirst(e);
return true;
}
public boolean offerLast(E e) {
addLast(e);
return true;
}
public E peekFirst() {
final Node f = first;
return (f == null) ? null : f.item;
}
public E peekLast() {
final Node l = last;
return (l == null) ? null : l.item;
}
public E pollFirst() {
final Node f = first;
return (f == null) ? null : unlinkFirst(f);
}
public E pollLast() {
final Node l = last;
return (l == null) ? null : unlinkLast(l);
}
public void push(E e) {
addFirst(e);
}
public E pop() {
return removeFirst();
}
public boolean removeFirstOccurrence(Object o) {
return remove(o);
}
public boolean removeLastOccurrence(Object o) {
if (o == null) {
// 如果o为null,则检索第一个值为null的结点,并调用unlink方法移除该元素
for (Node x = last; x != null; x = x.prev) {
if (x.item == null) {
unlink(x);
return true;
}
}
} else {
// 如果o不为null,则检索第一个值为o的结点,并调用unlink方法移除该元素
for (Node x = last; x != null; x = x.prev) {
if (o.equals(x.item)) {
unlink(x);
return true;
}
}
}
return false;
}
public ListIterator listIterator(int index) {
checkPositionIndex(index);
return new ListItr(index);
}
private class ListItr implements ListIterator {
private Node lastReturned;
private Node next;
private int nextIndex;
private int expectedModCount = modCount;
ListItr(int index) {
// assert isPositionIndex(index);
next = (index == size) ? null : node(index);
nextIndex = index;
}
public boolean hasNext() {
return nextIndex < size;
}
public E next() {
checkForComodification();
if (!hasNext())
throw new NoSuchElementException();
lastReturned = next;
next = next.next;
nextIndex++;
return lastReturned.item;
}
public boolean hasPrevious() {
return nextIndex > 0;
}
public E previous() {
checkForComodification();
if (!hasPrevious())
throw new NoSuchElementException();
lastReturned = next = (next == null) ? last : next.prev;
nextIndex--;
return lastReturned.item;
}
public int nextIndex() {
return nextIndex;
}
public int previousIndex() {
return nextIndex - 1;
}
public void remove() {
checkForComodification();
if (lastReturned == null)
throw new IllegalStateException();
Node lastNext = lastReturned.next;
unlink(lastReturned);
if (next == lastReturned)
next = lastNext;
else
nextIndex--;
lastReturned = null;
expectedModCount++;
}
public void set(E e) {
if (lastReturned == null)
throw new IllegalStateException();
checkForComodification();
lastReturned.item = e;
}
public void add(E e) {
checkForComodification();
lastReturned = null;
if (next == null)
linkLast(e);
else
linkBefore(e, next);
nextIndex++;
expectedModCount++;
}
public void forEachRemaining(Consumer super E> action) {
Objects.requireNonNull(action);
while (modCount == expectedModCount && nextIndex < size) {
action.accept(next.item);
lastReturned = next;
next = next.next;
nextIndex++;
}
checkForComodification();
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
public Iterator descendingIterator() {
return new DescendingIterator();
}
private class DescendingIterator implements Iterator {
private final ListItr itr = new ListItr(size());
public boolean hasNext() {
return itr.hasPrevious();
}
public E next() {
return itr.previous();
}
public void remove() {
itr.remove();
}
}
public Spliterator spliterator() {
return new LLSpliterator(this, -1, 0);
}
static final class LLSpliterator implements Spliterator {
static final int BATCH_UNIT = 1 << 10; // batch array size increment
static final int MAX_BATCH = 1 << 25; // max batch array size;
final LinkedList list; // null OK unless traversed
Node current; // current node; null until initialized
int est; // size estimate; -1 until first needed
int expectedModCount; // initialized when est set
int batch; // batch size for splits
LLSpliterator(LinkedList list, int est, int expectedModCount) {
this.list = list;
this.est = est;
this.expectedModCount = expectedModCount;
}
final int getEst() {
int s; // force initialization
final LinkedList lst;
if ((s = est) < 0) {
if ((lst = list) == null)
s = est = 0;
else {
expectedModCount = lst.modCount;
current = lst.first;
s = est = lst.size;
}
}
return s;
}
public long estimateSize() { return (long) getEst(); }
public Spliterator trySplit() {
Node p;
int s = getEst();
if (s > 1 && (p = current) != null) {
int n = batch + BATCH_UNIT;
if (n > s)
n = s;
if (n > MAX_BATCH)
n = MAX_BATCH;
Object[] a = new Object[n];
int j = 0;
do { a[j++] = p.item; } while ((p = p.next) != null && j < n);
current = p;
batch = j;
est = s - j;
return Spliterators.spliterator(a, 0, j, Spliterator.ORDERED);
}
return null;
}
public void forEachRemaining(Consumer super E> action) {
Node p; int n;
if (action == null) throw new NullPointerException();
if ((n = getEst()) > 0 && (p = current) != null) {
current = null;
est = 0;
do {
E e = p.item;
p = p.next;
action.accept(e);
} while (p != null && --n > 0);
}
if (list.modCount != expectedModCount)
throw new ConcurrentModificationException();
}
public boolean tryAdvance(Consumer super E> action) {
Node p;
if (action == null) throw new NullPointerException();
if (getEst() > 0 && (p = current) != null) {
--est;
E e = p.item;
current = p.next;
action.accept(e);
if (list.modCount != expectedModCount)
throw new ConcurrentModificationException();
return true;
}
return false;
}
public int characteristics() {
return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
}
}
public E removeFirst() {
final Node f = first;
if (f == null)
throw new NoSuchElementException();
return unlinkFirst(f);
}
public E remove() {
return removeFirst();
}
public E poll() {
final Node f = first;
return (f == null) ? null : unlinkFirst(f);
}
public E pollFirst() {
final Node f = first;
return (f == null) ? null : unlinkFirst(f);
}
public E pop() {
return removeFirst();
}