1.双链表结构
java
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable{
transient int size = 0;
transient Node<E> first;
transient Node<E> last;
public LinkedList() {
}
}
2.add
创建Node
更新last
更新老last的next
java
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable{
public boolean add(E e) {
linkLast(e);
return true;
}
void linkLast(E e) {
final Node<E> l = last;
//创建Node
//prev是last,next是null
final Node<E> newNode = new Node<>(l, e, null);
last = newNode; //更新last
if (l == null){//如果之前没有元素
first = newNode; //头也是新元素
} else{
l.next = newNode;
}
size++; //更新个数
modCount++;
}
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;
}
}
}
3.get
遍历的方式获得元素
java
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable{
public E get(int index) {
checkElementIndex(index); //判断index是否为有效范围内的index
return node(index).item;
}
Node<E> node(int index) {
// assert isElementIndex(index);
if (index < (size >> 1)) {//如果index小于size的一半,从first开始遍历
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;
}
}
}
4.remove index
先通过遍历的方式获得元素
然后将该元素从列表移除
java
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable{
public E remove(int index) {
checkElementIndex(index);
//node(index)找到index位置的node
return unlink(node(index));
}
//将找到的node从链表移除
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; //prev node next 移除node
x.prev = null;//把这个元素的prev赋值为null
}
if (next == null) {//找到的元素为最后一个元素
last = prev;
} else {
next.prev = prev;
x.next = null; //把这个元素的next赋值为null
}
x.item = null; //把这个元素的item赋值为null
size--;
modCount++;
return element;
}
}
5.remove object移除元素
遍历找到元素后,移动该元素
java
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable{
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;
}
}