public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
transient int size = 0;//LinkedList中元素的个数
transient Node<E> first;//头引用 //链表的头节点
transient Node<E> last;//尾引用 //链表的尾节点
public LinkedList() {//默认构造函数,创建一个空链表
}
public LinkedList(Collection<? extends E> c) {//按照c中的元素生成一个LinkedList
this();
addAll(c);//将c中的元素添加到空链表的尾部
}
private void linkFirst(E e) {
final Node<E> f = first;//头
final Node<E> newNode = new Node<>(null, e, f); //创建一个新结点,其前驱指针为空,后继指针指向first所指结点(可能为null)
first = newNode;//first指针始终指向链表的头
if (f == null)
last = newNode;
else
f.prev = newNode; //如果头插之前有结点,将其前驱指针指向新结点
size++;
modCount++; //记录修改次数,迭代时检测快速失败
}
void linkLast(E e) {
final Node<E> l = last;//尾
final Node<E> newNode = new Node<>(l, e, null); //创建一个新结点,其后继指针为空,前驱指针指向last所指结点(可能为null)
last = newNode;
if (l == null) //如果LinkedList刚创建,此时新创建的结点既然是尾结点也是头结点
first = newNode;
else
l.next = newNode; //如果尾插之前有结点,将其后继指针指向新结点
size++;
modCount++;
}
void linkBefore(E e, Node<E> succ) {//在非空节点succ之前插入新节点e
// assert succ != null;//外界调用需保证succ不为null,否则程序会抛出空指针异常
final Node<E> pred = succ.prev;
final Node<E> newNode = new Node<>(pred, e, succ);//生成一个新结点e,其前驱指针指向pred,后继指针指向succ
succ.prev = newNode;//succ的前驱指针指向newNode
if (pred == null)
first = newNode;//如果pred为null,则表示succ为头结点,此时头结点指向最新生成的结点newNode
else
pred.next = newNode;//pred的后继指针指向新生成的结点,此时已经完成了结点的插入操作
size++;
modCount++;
}
//头删法
private E unlinkFirst(Node<E> f) {
// assert f == first && f != null;//需确保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)//如果next为null,则表示f为last结点,此时链表即为空链表
last = null;
else
next.prev = null;//修改next的前驱指针为NULL,因为first结点的前驱指针为null
size--;
modCount++;
return 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;
}
E unlink(Node<E> x) {//删除节点x,并返回该节点的值
// assert x != null;//需确保x不为null,否则后续操作会抛出空指针异常
final E element = x.item;
final Node<E> next = x.next;
final Node<E> prev = x.prev;
if (prev == null) { //如果prev为空,则x结点为first结点,此时first结点指向next结点(x的后继结点)
first = next;
} else {
prev.next = next;//x的前驱结点的后继指针指向x的后继结点
x.prev = null;//gc
}
if (next == null) {//如果next结点为空,则x结点为尾部结点,此时last结点指向prev结点(x的前驱结点)
last = prev;
} else {
next.prev = prev;//x的后继结点的前驱指针指向x的前驱结点
x.next = null;//gc
}
x.item = null;//gc
size--;
modCount++;
return element;
}
public E getFirst() {//获得头结点的值
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return f.item;
}
public E getLast() {//获得尾结点的值
final Node<E> l = last;
if (l == null)
throw new NoSuchElementException();
return l.item;
}
public E removeFirst() {//删除头结点
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return unlinkFirst(f);
}
public E removeLast() {//删除尾结点
final Node<E> 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) {//判断元素(值为o)是否在链表中
return indexOf(o) != -1;//定位元素
}
public int size() {//返回元素个数
return size;
}
public boolean add(E e) {//向链表尾部添加元素e
linkLast(e);
return true;
}
public boolean remove(Object o) {//删除值为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;
}
public boolean addAll(Collection<? extends E> c) {//将集合c中所有元素添加到链表中
return addAll(size, c);
}
public boolean addAll(int index, Collection<? extends E> c) {//从index开始,向后添加集合c中的元素
checkPositionIndex(index);//判断index是否越界
Object[] a = c.toArray();//将集合c转换为数组
int numNew = a.length;
if (numNew == 0)
return false;
Node<E> pred, succ;
if (index == size) {//即a.length个节点在尾节点后面
succ = null;
pred = last;//pred指向尾节点
} else {
succ = node(index);//succ指向第index个节点
pred = succ.prev;//pred指向succ的前驱节点
}
for (Object o : a) {//for循环结束后,a里面的元素都添加到当前链表里了,向后添加
@SuppressWarnings("unchecked") E e = (E) o;
Node<E> newNode = new Node<>(pred, e, null);
if (pred == null)//如果pred为null,则succ为头结点
first = newNode;
else
pred.next = newNode;//pred的后继指针指向新节点
pred = newNode;//pred指向新节点,即往后移动一个节点,用于下一次循环
}
if (succ == null) {//succ为null表示index为尾节点之后
last = pred;
} else {
pred.next = succ;//pred表示所有元素添加好之后的最后那个节点,此时pred的后继指针指向之前记录的节点,即index处的节点
succ.prev = pred;//之前记录的结点指向添加元素之后的最后结点
}
size += numNew;
modCount++;
return true;
}
public void clear() {//清空链表
for (Node<E> x = first; x != null; ) {
Node<E> next = x.next;
x.item = null;//置空值,便于GC回收
x.next = null;//置空后继指针
x.prev = null;//置空前驱指针
x = next;
}
first = last = null;//释放头尾节点
size = 0;
modCount++;
}
public E get(int index) {//获得第index个节点的值
checkElementIndex(index);
return node(index).item;
}
public E set(int index, E element) {//设置第index个位置元素的值
checkElementIndex(index);
Node<E> x = node(index);
E oldVal = x.item;
x.item = element;
return oldVal;
}
public void add(int index, E element) {//在index处节点之前添加新的节点
checkPositionIndex(index);
if (index == size)
linkLast(element);
else
linkBefore(element, node(index));
}
public E remove(int index) {//删除第index个节点
checkElementIndex(index);
return unlink(node(index));
}
private boolean isElementIndex(int index) {//判断index是否为链表中的元素下标
return index >= 0 && index < size;
}
private boolean isPositionIndex(int index) {//判断index是否为链表中的元素下标,包含size位置
return index >= 0 && index <= size;
}
private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: "+size;
}
private void checkElementIndex(int index) {
if (!isElementIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
private void checkPositionIndex(int index) {
if (!isPositionIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
Node<E> node(int index) {//定位index处的节点
// assert isElementIndex(index);
if (index < (size >> 1)) {//index<size/2时,从头节点开始找
Node<E> x = first;
for (int i = 0; i < index; i++)
x = x.next;
return x;
} else {//index>=size/2时,从尾节点开始找
Node<E> x = last;
for (int i = size - 1; i > index; i--)
x = x.prev;
return x;
}
}
public int indexOf(Object o) {//返回首次出现指定元素值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;
}
public int lastIndexOf(Object o) {//返回最后一次出现指定元素值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;
}
//下面是与栈和队列相关的操作了
//实现栈的操作,获得栈顶元素
public E peek() {
final Node<E> f = first;
return (f == null) ? null : f.item;
}
public E element() {//实现队列操作,返回第一个节点
return getFirst();
}
public E poll() {//实现栈的操作,删除第一个节点
final Node<E> f = first;
return (f == null) ? null : unlinkFirst(f);
}
public E remove() {//实现队列操作,删除第一个节点
return removeFirst();
}
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<E> f = first;
return (f == null) ? null : f.item;
}
public E peekLast() {//返回尾节点的值
final Node<E> l = last;
return (l == null) ? null : l.item;
}
public E pollFirst() {//弹出头结点
final Node<E> f = first;
return (f == null) ? null : unlinkFirst(f);
}
public E pollLast() {//弹出尾节点
final Node<E> 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) {//删除第一次出现o的节点
return remove(o);
}
public boolean removeLastOccurrence(Object o) {//删除最后一次出现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;
}
public ListIterator<E> listIterator(int index) {
checkPositionIndex(index);
return new ListItr(index);//ListItr是一个双向迭代器
}
private class ListItr implements ListIterator<E> {//实现双向迭代器
private Node<E> lastReturned = null;//记录当前节点信息
private Node<E> 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++;//节点索引+1
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<E> 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++;
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
private static class Node<E> {//静态内部类
E item;//value
Node<E> next;//后继
Node<E> prev;//前驱
Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}
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();
}
}
@SuppressWarnings("unchecked")
private LinkedList<E> superClone() {
try {
return (LinkedList<E>) super.clone();
} catch (CloneNotSupportedException e) {
throw new InternalError();
}
}
public Object clone() {//克隆操作,执行浅拷贝,只复制引用,没有复制引用指向的内存
LinkedList<E> 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<E> x = first; x != null; x = x.next)
clone.add(x.item);
return clone;
}
public Object[] toArray() {//返回LinkedList的Object[]数组
Object[] result = new Object[size];
int i = 0;
for (Node<E> x = first; x != null; x = x.next)
result[i++] = x.item;
return result;
}
@SuppressWarnings("unchecked")
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;
}
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<E> 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());
}
}