类定义
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable
LinkedList继承了AbstractSequentialList,实现了List、Deque、Cloneable、Java.io.Serializable接口。从类定义可以看出LinkedList支持泛型,可序列化,并实现了List接口和Deque接口定义的方法。它是一种双向链表数据结构,由于双向链表的特性,它既具有线性表的特性也具有双端队列的特性;
用Deque实现栈
Stack是Vector的子类,从java1.0时就出现了,用于实现栈这种数据结构(FILO),即一种只能在一端进出元素的数据结构;但和Vector一样,Stack过于古老,并且实现地非常不好,问题多多,因此现在基本已经不用了;
Deque是Queue的子接口,表示双端队列,即两端(队尾和队首)都能插入和删除的特殊队列;因此可以直接用Deque来代替栈了,为了迎合Stack的风格,Deque还是提供了push/pop方法,让它用起来感觉是栈。只操作一端就是栈了。
/**
* Pushes an element onto the stack represented by this list. In other
* words, inserts the element at the front of this list.
*/
public void push(E e) {
addFirst(e);
}
/**
* Pops an element from the stack represented by this list. In other
* words, removes and returns the first element of this list.
*/
public E pop() {
return removeFirst();
}
全局变量
transient int size = 0;
/**
* Pointer to first node.
* Invariant: (first == null && last == null) ||
* (first.prev == null && first.item != null)
*/
transient Node<E> first;
/**
* Pointer to last node.
* Invariant: (first == null && last == null) ||
* (last.next == null && last.item != null)
*/
transient Node<E> last;
size维护着LinkedList对象存储的元素个数。
first是链表的头结点,last是链表的尾结点,它们本身都是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;
}
}
可以看出,Node对象是一个双向链表,它维护着自己的前一个节点和后一个节点的信息。
构造函数
/**
* Constructs an empty list.
*/
public LinkedList() {
}
/**
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
*/
public LinkedList(Collection<? extends E> c) {
this();
addAll(c);
}
LinkedList有一个默认构造函数,会创建一个空链表。
LinkedList还有一个带参构造函数,它可以将集合对象按照遍历的顺序转换为LinkedList链表。
实现的Deque接口方法
Deque是Queue的子接口,表示双端队列,既然是队列,有“先进先出”的特性,方法名不明确指出first和last的,基本都是“加队尾、删队头”。
linkFirst:在队首加入元素
void addFirst(E e);
boolean offerFirst(E e);
void push(E e); // 适配Stack,只在队首操作
linkLast:在队尾加入元素
boolean add(E e);
void addLast(E e);
boolean offer(E e);
boolean offerLast(E e);
unlinkFirst:删除队首元素
E remove(); // 异常不安全
E removeFirst(); // 异常不安全
E poll(); // 异常安全
E pollFirst(); // 异常安全
E pop(); // 异常不安全,适配Stack,只在队首操作
unlinkLast:删除队尾元素
E removeLast() // 异常不安全
E pollLast() // 异常安全
first.item:获取队首元素
E getFirst(); // 异常不安全
E peekFirst(); // 异常安全
E peekLast(); // 异常安全
E element(); // 异常不安全
E peek(); // 异常安全
last.item:获取队尾元素
E getLast(); // 异常不安全
其它特殊方法:
boolean removeFirstOccurrence(Object o);// 删除队列中第一个出现的e,成功删除返回true
boolean removeLastOccurrence(Object o);// 删除队列中最后一个出现的e,成功删除返回true
Iterator<E> iterator(); // 普通的正向迭代器,从队首向队尾迭代
Iterator<E> descendingIterator(); // 反向迭代器,从队尾向队首迭代
实现的List接口方法
addAll(int index, Collection<? extends E> c)
我们先看上面带参构造函数里用到的addAll方法。
/**
* 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.
*/
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;
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<E> 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 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;
}
}
/**
* 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;
}
}
该方法的功能是将集合参数插入链表中的指定位置上,这里要注意重新维护链表节点的前后指向关系。
首先检查index是否越界,至少不能超过当前链表的size。
将集合元素转化为数组,如果数组长度为0,方法返回false,这意味着没有元素可以用来添加。
然后定义了两个局部变量,succ维护着下一个元素,pred维护着上一个元素。
如果指定位置index等于链表长度size,那就是要将数组元素接在链表后,succ先置为null,pred指向链表的末尾元素last。
如果指定位置index小于链表长度size,那就是要将数组元素插入链表中,succ置为指定位置index上元素,而pred置为指定位置index上元素的前一个元素。
方法node(int index)就是返回指定位置上的链表元素。
下面遍历数组,将数组中的元素都包装为Node节点,Node节点的上一个元素是pred,下一个元素是null。
如果pred等于null,就意味着不存在前一个节点,也就是说新构造的节点newNode要放在链表的第一位,所以将fisrt指向newNode节点。
如果pred不等于null,意味着存在前一个节点,那么将前一个节点pred的下一个元素指向newNode。
绑定完前一个节点pred和newNode节点的关系,就要将pred重新指向newNode了,当前newNode作为下次遍历新构造的newNode节点的前一个元素了。
遍历完毕后,变量succ依然为null,意味着集合元素是接在原链表的末尾,那么变量pred维护的数组中最后一个元素就是链表的最后一个元素,将链表的末尾元素last指向变量pred。
遍历完毕后,变量succ不为null,succ存储着node(index)节点的信息。那么变量pred下一个元素要指向succ,node(index)节点的上一个元素要指向pred。
最后,维护链表长度,size要加上集合参数的长度。返回true,表示链表添加元素成功。
contains(Object o)
/**
* 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>.
*/
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.
*/
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;
}
该方法判断链表中是否包含元素。主要看indexOf方法。
如果传入对象是null,则遍历链表中节点,是否有节点的item值是null。index维护遍历链表的次数。
否则,遍历链表中节点,依次用equals方法比较传入对象obj和节点的item。index维护遍历链表的次数。
如果匹配,则返回index,不等于-1返回真。如果不匹配,返回假。
toArray()
/**
* Returns an array containing all of the elements in this list
* in proper sequence (from first to last element).
*
* <p>The returned array will be "safe" in that no references to it are
* maintained by this list. (In other words, this method must allocate
* a new array). The caller is thus free to modify the returned array.
*
* <p>This method acts as bridge between array-based and collection-based
* APIs.
*/
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;
}
遍历链表中节点,将节点依次放入数组中。
add(E e)
/**
* Appends the specified element to the end of this list.
*/
public boolean add(E e) {
linkLast(e);
return true;
}
/**
* 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++;
}
(1)将待添加节点指向末尾节点last,然后将新节点newNode设为last,表示是链表的最新末尾节点。
(2)新节点newNode指向前一个元素设置完,再来设置前一个元素指向新节点newNode。l.next = newNode;
(3)当然,之前的末尾节点last是null,意味着新增节点就是表头节点了,将newNode设为first。
remove(Object o)
/**
* Removes the first occurrence of the specified element from this list,
* if it is present. If this list does not contain the element, it is
* unchanged. More formally, removes the element with the lowest index
* {@code i} such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>
* (if such an element exists). Returns {@code true} if this list
* contained the specified element (or equivalently, if this list
* changed as a result of the call).
*/
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;
}
与indexOf方法相似,如果删除元素是null,则遍历节点看看哪个节点的item值是null;如果删除元素不是null,则用equals方法比较节点item值和删除元素是否相等。相同的也是重点的是unlink方法。
/**
* 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;
}
(1)定位到节点x后,获取其前一个节点prev和后一个节点next。
(2)如果prev是null,说明节点x是第一个节点,那么删除x后,第一个节点会变成节点next。first = next;
(3)如果prev不是null,那么删除节点x后,节点prev直接指向节点next;同时,节点x不再指向prev,直接置为null。x.prev = null;
(4)如果next是null,说明节点x是最后一个节点,那么删除x后,prev就是最后一个节点,将prev指向last。last = prev。
(5)如果next不是null,那么删除节点x后,节点next直接指向节点prev;同时,节点x不再指向next,直接置为null。x.next = null;
(6)将节点x本身的item值设为null,返回被删除元素。
addAll(Collection<? extends E> 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.)
*/
public boolean addAll(Collection<? extends E> c) {
return addAll(size, c);
}
调用了最上面的方法addAll(int index, Collection<? extends E> c)
,不再赘述。
clear()
/**
* Removes all of the elements from this list.
* The list will be empty after this call returns.
*/
public void clear() {
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++;
}
从第一个节点开始,遍历链表,将所有节点的前后指向、item值都置为null。同时将first和last置为null,链表长度置为0。
get(int index)
/**
* Returns the element at the specified position in this list.
*/
public E get(int index) {
checkElementIndex(index);
return node(index).item;
}
获得指定位置上的节点。首先校验index是否越界,然后遍历链表返回指定位置节点的item。
不过为了效率,会比较index处于链表的前端还是后端,如果处于前半,就从头遍历;如果出于后半,就从后往前遍历。
set(int index, E element)
/**
* Replaces the element at the specified position in this list with the
* specified element.
*/
public E set(int index, E element) {
checkElementIndex(index);
Node<E> x = node(index);
E oldVal = x.item;
x.item = element;
return oldVal;
}
替换指定位置上的节点。替换时,只替换节点的item,节点的前后节点指向关系不用改变。方法执行时首先校验index是否越界。最后返回被替换节点的item值。
add(int index, E element)
/**
* Inserts the specified element at the specified position in this list.
* Shifts the element currently at that position (if any) and any
* subsequent elements to the right (adds one to their indices).
*/
public void add(int index, E element) {
checkPositionIndex(index);
if (index == size)
linkLast(element);
else
linkBefore(element, node(index));
}
/**
* Inserts element e before non-null Node succ.
*/
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++;
}
在指定位置添加元素。校验index是否越界后,这里做了一个判断,如果index是链表长度size,也就是说在链表末尾添加元素,那方法等效add(E e)
。
如果在链表中间添加节点,则调用linkBefore方法。通过node(index)
获取到index位置节点的下一个节点succ,succ节点向前指向index位置上的节点pred,新增元素newNode就是要夹在pred和succ之间嘛。下面再把succ向前指向newNode,prev向后指向newNode即可(如果prev是null,newNode就是头节点了)。
remove(int index)
/**
* Removes the element at the specified position in this list. Shifts any
* subsequent elements to the left (subtracts one from their indices).
* Returns the element that was removed from the list.
*/
public E remove(int index) {
checkElementIndex(index);
return unlink(node(index));
}
删除指定位置上的节点。校验完index是否越界后,就调用unlink方法。具体解析参见方法remove(Object o)
。
indexOf(Object o)
contains(Object o)
方法中已解释过,不再赘述。
lastIndexOf(Object o)
/**
* 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.
*/
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;
}
与indexOf(Object o)
方法的区别是,遍历节点从后往前。
listIterator(int index)
/**
* Returns a list-iterator of the elements in this list (in proper
* sequence), starting at the specified position in the list.
* Obeys the general contract of {@code List.listIterator(int)}.<p>
*
* The list-iterator is <i>fail-fast</i>: if the list is structurally
* modified at any time after the Iterator is created, in any way except
* through the list-iterator's own {@code remove} or {@code add}
* methods, the list-iterator will throw a
* {@code ConcurrentModificationException}. Thus, in the face of
* concurrent modification, the iterator fails quickly and cleanly, rather
* than risking arbitrary, non-deterministic behavior at an undetermined
* time in the future.
*/
public ListIterator<E> listIterator(int index) {
checkPositionIndex(index);
return new ListItr(index);
}
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;
}
// 其它代码略去
}
从指定位置开始,返回一个list迭代器。
我们比较一下Iterator和ListIterator迭代器:
(1)Iterator可以应用于所有的Collection集合,而ListIterator只能用于List及其子类型。
(2)ListIterator有add方法,可以向List中添加对象,而Iterator不能。
(3)ListIterator和Iterator都有hasNext()和next()方法,可以实现顺序向后遍历,但是ListIterator有hasPrevious()和previous()方法,可以实现逆向(顺序向前)遍历。
(4)ListIterator可以定位当前索引的位置,nextIndex()和previousIndex()可以实现。Iterator没有此功能。
(5)都可实现删除操作,但是ListIterator可以实现对象的修改,set()方法可以实现。Iterator仅能遍历,不能修改。