LinkedList
All of the operations perform as could be expected for a doubly-linked list. Operations that index into the list will traverse the list from the beginning or the end, whichever is closer to the specified index.
一种线性表
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable
属性
// 链表元素存储大小
transient int size = 0;
// 双向链表头节点
transient LinkedList.Node<E> first;
// 双向链表尾节点
transient LinkedList.Node<E> last;
Node则是LinkedList私有的静态内部类,用来存放数据
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;
}
}
构造方法
LinkedList共有两个构造方法:
public LinkedList() {}
public LinkedList(Collection<? extends E> c) {}
第一个就是空的无参构造方法,没啥好说的。
第二个构造方法传入一个Collection对象:
public LinkedList(Collection<? extends E> c) {
this();
addAll(c);
}
addAll将传入的Collection对象插入到链表中。
public boolean addAll(Collection<? extends E> c) {
return addAll(size, c);
}
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;
//如果插入的位置与size相同,则将集合c中的元素插到尾部
if (index == size) {
succ = null;
pred = last;
//相反,找到index所在位置的指针
//succ指向index所在位置
//pred则执行index的前一个节点
} 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;
}
一些方法
add
还是从add开始:
public boolean add(E e) {
linkLast(e);
return true;
}
调用linkLast方法
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++;
}
代码逻辑十分清晰,直接在链表尾部插入。
其实在之前构造方法那儿还看到了add的另外一个重载方法,它分别调用linkLast以及linkBefore实现从尾部以及首部插入元素:
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++;
}
node
通过传入的int值返回链表在该位置的元素
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的一般小,则从头开始比较,如果大则从尾开始比较
offer
就相当于add
public boolean offer(E e) {
return add(e);
}
peek
peek是弹出链表首部元素,但不删除
public E peek() {
final Node<E> f = first;
return (f == null) ? null : f.item;
}
poll
poll也是弹出链表首部元素,但是它会同时删除首部元素
public E poll() {
final Node<E> f = first;
return (f == null) ? null : unlinkFirst(f);
}
其他种种基本一看就会,这里就不说了。
网友评论