您的位置:首页 > 编程语言 > Java开发

java源码分析08-LinkedList

2015-11-14 22:18 471 查看
喜欢一个人,就会喜欢她的一切吗?

今天,我们来看下LinkedList的结构。



LinkedList内部其实是双向链表实现的,而且拥有轮询以及出栈的功能。

增删改查:

public boolean add(E e) {
linkLast(e);
return true;
}
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之后需要将size加一,modCount也需要加一。

public E get(int index) {
checkElementIndex(index);
return node(index).item;
}
private void checkElementIndex(int index) {
if (!isElementIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
private boolean isElementIndex(int index) {
return index >= 0 && index < size;
}


查询的时候,需要先检查是否为有效查询,也就是下标是否在0与size-1之间。

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;
}


此处有一个优化,首先判断下标是在中间节点的左边还是右边,如果在左边就从头结点开始遍历;否则从尾结点开始遍历查询。

轮询机制

public E poll() {
final Node<E> f = first;
return (f == null) ? null : unlinkFirst(f);
}


此处为什么定义一个final类型的引用,而没有直接unlinkFirst(first)?

private E unlinkFirst(Node<E> f) {
// assert f == first && 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)
last = null;
else
next.prev = null;
size--;
modCount++;
return element;
}


删除头结点,第一步,提前存储头结点的后继;第二,头结点的值设为null,其下一节点为null;第三,将first指向之前存储的已删除节点的后继。第四,判断后继是否为空,为空那么last为null,否则后继的前驱为null。

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: