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;}}
对于add 添加数据的代码,就是调用这个方法
publicvoidadd(int index, E element){checkPositionIndex(index);if(index == size)linkLast(element);elselinkBefore(element,node(index));}
voidlinkLast(E e){final Node<E> l = last;// 1. 首先创建一个新的节点,而1 和 last 指向原来的尾结点,如果原链表为空,则为nullfinal Node<E> newNode =newNode<>(l, e, null);// 2. 修改 尾结点last ,指向 新的最后尾结点
last = newNode;// 3. 修改前节点的后向连接,如果原来链表为空,则让头结点指向新节点,否则让前一个结点的next指向新节点if(l == null)
first = newNode;else
l.next = newNode;
size++;
modCount++;}
voidlinkBefore(E e, Node<E> succ){// assert succ != null;final Node<E> pred = succ.prev;final Node<E> newNode =newNode<>(pred, e, succ);
succ.prev = newNode;if(pred == null)
first = newNode;else
pred.next = newNode;
size++;
modCount++;}
根据内容查找元素indexof
publicintindexOf(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;}
根据索引来查找值
public E get(int index){//检查索引位置的有效性checkElementIndex(index);returnnode(index).item;}
删除元素 remove
publicbooleanremove(Object o){if(o == null){for(Node<E> x = first; x != null; x = x.next){if(x.item == null){unlink(x);returntrue;}}}else{for(Node<E> x = first; x != null; x = x.next){if(o.equals(x.item)){unlink(x);returntrue;}}}returnfalse;}
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;if(prev == null){
first = next;}else{
prev.next = next;
x.prev = null;}if(next == null){
last = prev;}else{
next.prev = prev;
x.next = null;}
x.item = null;
size--;
modCount++;return element;}