用java源代码学数据结构<四>: LinkedList 详解(二)
= prev;
if (prev == null)
first = null;
else
prev.next = null;
size--;
modCount++;
return element;
}
//删除指点节点x
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的前节点设置为null
x.prev = null;
}
if (next == null) {
last = prev;
} else {
next.prev = prev;
//将节点x的后节点设置为null
x.next = null;
}
//x的prev、item、next都为Null,gc就可以回收了
x.item = null;
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;
}
//默认的add是向链表末尾增加元素
public boolean add(E e) {
linkLast(e);
return true;
}
//删除指定元素
public boolean remove(Object o) {
//对于o是否null进行两种比较
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;
}
public boolean addAll(Collection< extends E> c) {
return addAll(size, c);
}
public boolean addAll(int index, Collection< extends E> c) {
//index参数检查
checkPositionIndex(index);
Object[] a = c.toArray();
int numNew = a.length;
if (numNew == 0)
return false;
Node pred, succ;
//如果是在链表末尾插入,将pred设置为last
if (index == size) {
succ = null;
pred = last;
} else {
//否则使用succ暂时保存插入位置后面的一个节点
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)
first = newNode;
else
pred.next = newNode;
pre