链表节点
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;
}
}
添加方法
在链表结尾插入新节点
public boolean add(E e) {
linkLast(e);
return true;
}
void linkLast(E e) {
final Node<E> l = last;
// 用当前元素创建新节点,并指定新节点的prev=最后一个节点
final Node<E> newNode = new Node<>(l, e, null);
last = newNode;
// 如果原链表是空的,那么把新节点当作第一个节点
if (l == null)
first = newNode;
else
// 否则,最后一个节点的next=新节点
l.next = newNode;
size++;
modCount++;
}
将新节点作为链表的第一个节点
public void addFirst(E e) {
linkFirst(e);
}
private void linkFirst(E e) {
final Node<E> f = first;
// newNode.prev=null;newNode.next=first;
final Node<E> newNode = new Node<>(null, e, f);
first = newNode;
// 链表为空,新节点作为最后一个节点
if (f == null)
last = newNode;
else
// 否则原头节点的prev=newNode
f.prev = newNode;
size++;
modCount++;
}
添加方法就写这么多了,有兴趣的自己看其他的,都是一个原理,链表节点的操作。
获取方法
获取链表指定索引位置的元素
public E get(int index) {
// 检查index是否在[0-list.size)范围内,如果不在抛出IndexOutOfBoundsException
checkElementIndex(index);
// 返回索引位置的元素
return node(index).item;
}
Node<E> node(int index) {
// assert isElementIndex(index);
// index在左半部分,那么从[0,index)之间遍历
if (index < (size >> 1)) {
Node<E> x = first;
for (int i = 0; i < index; i++)
x = x.next;
return x;
} else {
// index在右半部分,那么从[size-1,index)之间从后往前遍历
Node<E> x = last;
for (int i = size - 1; i > index; i--)
x = x.prev;
return x;
}
}
LinkedList在获取元素的时候,把链表一分为二去找index,尽可能减少遍历元素的个数
删除方法
public boolean remove(Object o) {
// ========查找null元素 START========
if (o == null) {
for (Node<E> x = first; x != null; x = x.next) {
if (x.item == null) {
// 删除找到的元素
unlink(x);
return true;
}
}
// ========查找null元素 END========
} else {
for (Node<E> x = first; x != null; x = x.next) {
if (o.equals(x.item)) {
unlink(x);
return true;
}
}
}
return false;
}
删除指定元素的unlink方法
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;
// ========节点前继节点处理 START========
if (prev == null) {
// 要删除的节点是第一个节点,把要删除的节点的next节点当作第一个节点
first = next;
} else {
prev.next = next;
x.prev = null;
}
// ========节点前继节点处理 END========
// ========节点后继节点处理 START========
if (next == null) {
// 要删除的节点是最后一个节点,把要删除的节点的prev当作最后一个节点
last = prev;
} else {
next.prev = prev;
x.next = null;
}
// ========节点后继节点处理 END========
x.item = null;
size--;
modCount++;
return element;
}
网友评论