我们知道java里面的LinkedList的底层数据结构也是基于链表的,是一个队列来实现的,我们下面就来看看源码的具体实现思路:
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
// 链表的长度
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;
}
// 借点内部类,包括指向前驱以及后继的节点,实际上就是双向链表,
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;
}
}
//看它的remove方法
public boolean remove(Object o) {
if (o == null) {
for (Node<E> x = first; x != null; x = x.next) {
if (x.item == null) {
unlink(x);
return true;
}
}
} else {
for (Node<E> x = first; x != null; x = x.next) {
if (o.equals(x.item)) {
unlink(x);
return true;
}
}
}
// 其实逻辑很简单,就是一个一个的遍历,判断是否相等然后移除
return false;
}
//移除逻辑,就是要斩断连接移除节点的两根线
E unlink(Node<E> x) {
// assert x != null;
final E element = x.item;
// 获取到前后节点
final Node<E> next = x.next;
final Node<E> prev = x.prev;
// 处理前驱
// 如果处于第一个位置,那么将头指针first指向它的下一个next
// 不在第一个位置,将前面节点的next指向该节点的next
if (prev == null) {
first = next;
} else {
prev.next = next;
x.prev = null;
}
//处理后继节点
//如果是最后一个位置,将last指针移到前一个位置
//不在最后一个位置,将后面的节点的前驱指向该节点的前驱
if (next == null) {
last = prev;
} else {
next.prev = prev;
x.next = null;
}
x.item = null;
size--;
modCount++;
return element;
}
//添加节点到末尾,
public boolean add(E e) {
linkLast(e);
return true;
}
void linkLast(E e) {
//获取链表的最后一个节点
final Node<E> l = last;
//构造一个新的节点,指向前驱l
final Node<E> newNode = new Node<>(l, e, null);
//给尾节点赋值
last = newNode;
// 如果链表为空,没有尾节点,那么新的节点是第一个节点,first,last节点都指向它,否则将该节点添加到l节点后面
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
modCount++;
}
看到这里大概就知道LinkedList的实现思路了,就是定义了节点对象,有pre,data,next域,LinkedList定义了first,last来标记头尾元素,增删改查只需要通过first,last指针来定位到具体的位置,然后在然后再进行操作!