本文将结合源代码简单介绍一下java 中LinkedList的实现。
继承结构
相比ArrayList,LinkedList的继承结构要复杂一些,可以看出,LinkedList还是双向队列的实现。也意味着LinkedList可以作为栈使用。
重要的字段
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;
其实LinkedList中一共只声明了3个字段,非常简洁,分别是表示长度的size,头节点和尾节点。
节点的定义
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;
}
}
可以看到是一个非常简单的定义,只有一个构造函数,是一个经典的双端链表的节点的定义。
重要方法的实现
- add(E)
这个方法向链表中插入一个元素,注意使用的方法是尾插法,具体实现如下:
/**
* Appends the specified element to the end of this list.
*
* <p>This method is equivalent to {@link #addLast}.
*
* @param e element to be appended to this list
* @return {@code true} (as specified by {@link Collection#add})
*/
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++;
}
2 addFirst(E)
向链表的头部插入一个数据
/**
* Inserts the specified element at the beginning of this list.
*
* @param e the element to add
*/
public void addFirst(E e) {
linkFirst(e);
}
/**
* Links e as first element.
*/
private void linkFirst(E e) {
final Node<E> f = first;
final Node<E> newNode = new Node<>(null, e, f);
first = newNode;
if (f == null)
last = newNode;
else
f.prev = newNode;
size++;
modCount++;
}
简单的头插法插入实现。
3 node(index)
返回位于index处的节点,这个是LinkedList查找的实现函数,所有带查找操作的函数均以此实现。
/**
* Returns the (non-null) Node at the specified element index.
*/
Node<E> node(int 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;
}
}
从源代码中可以看出,查找的操作根据查找的位置进行了优化,要是查找小于size/2的就从头开始,反之则从尾指针开始。
作为队列和栈使用
作为队列使用
向队尾加入offer(E)
查询队头并移除poll()
查询队头但不移除peek()
作为栈使用
压栈 push(E)
出栈 pop()