LinkedList
Queue:接口,声明了队列的共性功能,表明有队列的特性
Deque:接口,表明有双端队列的特性,
AbstractSequentialList:抽象类,定义了次序访问,表明是链表实现,适合使用迭代器遍历
/*https://www.cnblogs.com/xujian2014/p/4630785.html */
public class LinkedList
extends AbstractSequentialList
implements List, Deque, Cloneable, java.io.Serializable
{
/*当前有多少个节点,禁止序列化*/
transient int size = 0;
/*头节点*/
transient Node first;
/*尾节点*/
transient Node last;
/*空构造方法*/
public LinkedList() {
}
/* 构造方法,初始化给定的集合:当c为空时,抛出NullPointerException * */
public LinkedList(Collection extends E> c) {
this();
addAll(c);
}
/*将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++;//修改次数增加
}
/*将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++;//修改次数增加
}
/*将e插入到非空的succ元素前面*/
void linkBefore(E e, Node succ) {
// assert succ != null;
final Node pred = succ.prev;/*保存succ的前节点*/
/*获得一个前节点为pred,指向元素为e,后置节点为succ的节点*/
final Node newNode = new Node<>(pred, e, succ);
succ.prev = newNode;/*将succ的前节点指向新产生的节点*/
if (pred == null)//如果succ时第一个节点:头节点
first = newNode;
else //如果succ不是第一个节点 :头节点
pred.next = newNode;
size++; //链表节点数++
modCount++; //链表的修改次数++
}
/*去掉第一个节点*/
private E unlinkFirst(Node f) {
// assert f == first && f != null;
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;//返回被去掉的节点元素
}
/*删除最后一个节点*/
private E unlinkLast(Node l) {
// assert l == last && l != null;
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;//被删除的节点里的元素
}
/*删除指定元素*/
E unlink(Node x) {
// assert x != null;
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 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);
}
/*删除最后一个节点*/
public E removeLast() {
final Node l = last;
if (l == null)
throw new NoSuchElementException();
return unlinkLast(l);
}
/*在表头添加一个元素*/
public void addFirst(E e) {
linkFirst(e);
}
/*在最后添加一个元素*/
public void addLast(E e) {
linkLast(e);
}
/*判断是否包含这个元素*/
public boolean contains(Object o) {
return indexOf(o) != -1;
}
/*获得当前链表包含的元素*/
public int size() {
return size;
}
/*添加元素,最尾部添加*/
public boolean add(E e) {
linkLast(e);
return true;
}
/*删除第一个指定元素*/
public boolean remove(Object o) {
if (o == null) {/*允许有多个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;/*返回是否删除*/
}
/*批量添加元素*/
public boolean addAll(Collection extends E> c) {
return addAll(size, c);
}
/*从指定位置开始批量添加元素*/
public boolean addAll(int index, Collection extends E> c) {
checkPositionIndex(index);/*检查是否有效index*/
Object[] a = c.toArray();
int numNew = a.length;
if (numNew == 0)
return false;
Node pred, succ;
if (index == size) {/*如果是在尾部添加元素*/
succ = null;
pred = last;
} else {/*在指定位置添加元素*/
succ = node(index);/*获取位置元素*/
pred = succ.prev;
}
for (Object o : a) {/*遍历要添加的元素集合*/
@SuppressWarnings("unchecked") E e = (E) o;
Node newNode = new Node<>(pred, e, null);
if (pred == null)/*如果是从0位置开始添加*/
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;/*返回添加是否成功*/
}
/*清除链表*/
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 x = first; x != null; ) {/*把所有的元素置为空 gc*/
Node next = x.next;
x.item = null;
x.next = null;
x.prev = null;
x = next;
}
first = last = null;
size = 0;
modCount++;
}
// Positional Access Operations
/*获取指定节点储存的元素,index必须有效*/
public E get(int index) {
checkElementIndex(index);
return node(index).item;
}
/*设置指定index的节点元素*/
public E set(int index, E element) {
checkElementIndex(index);
Node x = node(index);
E oldVal = x.item;
x.item = element;
return oldVal;/*返回修改之前的元素*/
}
/*在指定的index添加元素*/
public void add(int index, E element) {
checkPositionIndex(index);
if (index == size)
linkLast(element);
else
linkBefore(element, node(index));
}
/*删除指定index的节点*/
public E remove(int index) {
checkElementIndex(index);
return unlink(node(index));/*返回倍删除节点的元素*/
}
/*检查元素index是否在有效范围内*/
private boolean isElementIndex(int index) {
return index >= 0 && index < size;
}
/*检查index时候有效*/
private boolean isPositionIndex(int index) {
return index >= 0 && index <= size;
}
/*index不合法是的提示信息*/
private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: "+size;
}
/*检查index*/
private void checkElementIndex(int index) {
if (!isElementIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
/*检查index是否有效,抛出IndexOutOfBoundsException异常*/
private void checkPositionIndex(int index) {
if (!isPositionIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
/*获取指定index的节点*/
Node node(int index) {
// assert isElementIndex(index);
if (index < (size >> 1)) {/*如果从前半部分添加*/
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;
}
}
// Search Operations
/*获取指定元素的在链表中的第一个index*/
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;/*没找到返回-1*/
}
/*获取指定元素的最大的index*/
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;/*为找到返回-1*/
}
// Queue operations.
/*获取第一个元素的值*/
public E peek() {
final Node f = first;
return (f == null) ? null : f.item;
}
/*获取第一个节点的值*/
public E element() {
return getFirst();
}
/*获取第一个节点的值并删除第一个节点*/
public E poll() {
final Node f = first;
return (f == null) ? null : unlinkFirst(f);
}
/*删除第一个节点,返回删除的节点的值*/
public E remove() {
return removeFirst();
}
/*在链表尾部添加e*/
public boolean offer(E e) {
return add(e);
}
// Deque operations
/*在链表头添加一个元素*/
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();
}
/*删除第一个出现的o*/
public boolean removeFirstOccurrence(Object o) {
return remove(o);
}
/*删除最后一次出现的o*/
public boolean removeLastOccurrence(Object o) {
if (o == null) {
for (Node x = last; x != null; x = x.prev) {
if (x.item == null) {
unlink(x);
return true;
}
}
} else {
for (Node x = last; x != null; x = x.prev) {
if (o.equals(x.item)) {
unlink(x);
return true;
}
}
}
return false;
}
/*https://www.cnblogs.com/ITtangtang/p/3948610.html#a10*/
/*创建迭代器指定起始位置*/
public ListIterator listIterator(int index) {
checkPositionIndex(index);
return new ListItr(index);
}
/*实现ListIterator,使用list迭代对象时使用*/
private class ListItr implements ListIterator {
private Node lastReturned;/*最近一次返回的节点,也是当前持有的节点*/
private Node next;/*对下一个元素的引用*/
private int nextIndex;/*下一个节点的index*/
private int expectedModCount = modCount;
ListItr(int index) {
// assert isPositionIndex(index);
next = (index == size) ? null : node(index);
nextIndex = index;
}
/*根据nextIndex是否等于size判断时候还有下一个节点*/
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();
}
}
/*链表单个节点*/
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 Iterator descendingIterator() {
return new DescendingIterator();
}
/*反向的Iterator*/
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();
}
}
/*https://blog.csdn.net/m0_37884977/article/details/80467658*/
/*克隆的辅助方法*/
@SuppressWarnings("unchecked")
private LinkedList superClone() {
try {
return (LinkedList) super.clone();
} catch (CloneNotSupportedException e) {
throw new InternalError(e);
}
}
/*重写的clone*/
public Object clone() {
LinkedList clone = superClone();
// Put clone into "virgin" state
clone.first = clone.last = null;
clone.size = 0;
clone.modCount = 0;
/*把链表中的元素复制过去*/
// Initialize clone with our elements
for (Node x = first; x != null; x = x.next)
clone.add(x.item);
return clone;
}
/*将链表转化成数组*/
public Object[] toArray() {
Object[] result = new Object[size];
int i = 0;
for (Node x = first; x != null; x = x.next)
result[i++] = x.item;
return result;
}
/*返回指定类型的Array*/
@SuppressWarnings("unchecked")
public 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 x = first; x != null; x = x.next)
result[i++] = x.item;
if (a.length > size)
a[size] = null;
return a;
}
private static final long serialVersionUID = 876323262645176354L;
/*重写的序列化方法*/
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 x = first; x != null; x = x.next)
s.writeObject(x.item);
}
/*重写反序列化方法*/
@SuppressWarnings("unchecked")
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());
}
/*获取一个可分割迭代器*/
@Override
public Spliterator spliterator() {
return new LLSpliterator(this, -1, 0);
}
/*https://blog.csdn.net/jiangmingzhi23/article/details/78927552*/
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;
}
}
}