用java源代码学数据结构<四>: LinkedList 详解(四)
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;//防止空指针异常
}
// 获取但不移除此列表的头(第一个元素)。
public E element() {
return getFirst();
}
//获取并"移除"此列表的头(第一个元素)
public E poll() {
final Node f = first;
return (f == null) null : unlinkFirst(f);
}
//获取并"移除"此列表的头(第一个元素)。
public E remove() {
return removeFirst();
}
//将指定元素添加到此列表的末尾(最后一个元素)。
public boolean offer(E e) {
return add(e);
}
//在此列表的开头插入指定的元素。
public boolean offerFirst(E e) {
addFirst(e);
return true;
}
//在此列表末尾插入指定的元素
public boolean offerLast(E e) {
addLast(e);
return true;
}
// 获取但不移除此列表的第一个元素;如果此列表为空,则返回 null。
// 感觉跟peek一样
public E peekFirst() {
final Node f = first;
return (f == null) null : f.item;
}
//获取但不移除此列表的最后一个元素;如果此列表为空,则返回 null。
public E peekLast() {
final Node l = last;
return (l == null) null : l.item;
}
// 获取并移除此列表的第一个元素;如果此列表为空,则返回 null。
public E pollFirst() {
final Node f = first;
return (f == null) null : unlinkFirst(f);
}
//获取并移除此列表的最后一个元素;如果此列表为空,则返回 null。
public E pollLast() {
final Node l = last;
return (l == null) null : unlinkLast(l);
}
//将e对象加到头部
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) {
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;
}
public ListIterator listIterator(int index) {
checkPositionIndex(index);
return new ListItr(index);
}
private class ListItr implements ListIterator {
//类似于Vector中的lastRet,用于remove,表示上次迭代(不分next,preivous)返回的对象
private Node lastReturned = null;
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();