le284 发表于3年前
• 发表于 3年前
• 阅读 306
• 收藏 8
• 评论 0

``````	transient int size = 0;
transient Node<E> first; //链表的头指针
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;
}
}
``````

##链表增加元素

``````	// 在连表头添加元素, 简单的链表操作
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++;
}

//添加尾节点什么的都类似就不多赘述
``````

##链表删除元素

``````	//删除节点, 关键点就是x.prev.next = x.next; x.next.prev = x.prev; 其余删除方法都类似
// 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;
}
``````

##查询某个元素

``````	//代码也很简单; 遍历整个链表
public int indexOf(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;
}
``````

## 获取index的元素

``````	//跟indexof()类似
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;
}
}
``````

×