doubly-linked list implementation of the list and deque interfaces. implements all optional list operations, and permits all elements (including null).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.note that this implementation is not synchronized. if multiple threads access a linked list concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. (a structural modification is any operation that adds or deletes one or more elements; merely setting the value of an element is not a structural modification.) this is typically accomplished by synchronizing on some object that naturally encapsulates the list.
当向表头插入一个节点时,很显然当前节点的前驱一定为 null,而后继结点是 first 指针指向的节点,当然还要修改 first 指针指向新的头节点。除此之外,原来的头节点变成了第二个节点,所以还要修改原来头节点的前驱指针,使它指向表头节点,源码的实现如下:
private void linkfirst(e e) {
final node<e> f = first;
//当前节点的前驱指向 null,后继指针原来的头节点
final node<e> newnode = new node<>(null, e, f);
//头指针指向新的头节点
first = newnode;
//如果原来有头节点,则更新原来节点的前驱指针,否则更新尾指针
if (f == null)
last = newnode;
else
f.prev = newnode;
size++;
modcount++;
}
在表尾添加元素跟在表头添加元素大同小异,如图所示
当向表尾插入一个节点时,很显然当前节点的后继一定为 null,而前驱结点是 last指针指向的节点,然后还要修改 last 指针指向新的尾节点。此外,还要修改原来尾节点的后继指针,使它指向新的尾节点,源码的实现如下:
void linklast(e e) {
final node<e> l = last;
//当前节点的前驱指向尾节点,后继指向 null
final node<e> newnode = new node<>(l, e, null);
//尾指针指向新的尾节点
last = newnode;
//如果原来有尾节点,则更新原来节点的后继指针,否则更新头指针
if (l == null)
first = newnode;
else
l.next = newnode;
size++;
modcount++;
}