LinkedList源码分析(一)

List代码中有大量的transient修饰,用transient修饰的变量,序列化时会忽略。

transient Node<E> first;

1、add方法

public boolean add(E e) {
      linkLast(e);
       return true;
 }

点击linkLast进入如下代码

void linkLast(E e) {
    final Node<E> l = last;
     final Node<E> newNode = new Node<>(l, e, null);
     last = newNode;
     if (l == null)      //如果原先的last节点为null,则新节点为first,否则用其next指向新节点
         first = newNode;
     else
         l.next = newNode;
     size++;
     modCount++;
}

其中这行代码,构建新节点,第1个参数表示prev指针,这里为last;第2个参数表示节点内容数据;第3个参数表示next指针

final Node<E> newNode = new Node<>(l, e, null);    

这行代码,将last指向最新创建的节点

 last = newNode;

2、addFirst方法

public void addFirst(E e) {
        linkFirst(e);
}

点击linkFirst(e)进入如下代码:

private void linkFirst(E e) {
     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;   //如果原先的first不为空,则用其前指针指向新节点
     size++;
     modCount++;
}

这行代码,创建一个新节点,其右指针指向原先的first节点。

final Node<E> newNode = new Node<>(null, e, f);

3、add(int index, E element)方法

1)入口
public void add(int index, E element) {
     checkPositionIndex(index);

     if (index == size)
         linkLast(element);      //插到队尾
     else
         linkBefore(element, node(index));
}

这行代码,是检查当前index是否合法,点击进入步骤2)

checkPositionIndex(index) 

根据index拿到对应的节点,点击进入步骤4)

node(index)

这行代码是拿到当前index对应的节点,将新节点插入到他前面。点击进入步骤5)

 linkBefore(element, node(index));
2)checkPositionIndex方法
private void checkPositionIndex(int index) {
   if (!isPositionIndex(index))
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}

点击isPositionIndex方法进入如下代码

3)isPositionIndex方法
private boolean isPositionIndex(int index) {
        return index >= 0 && index <= size;
 }
4)node(int index)

这段代码,根据下标,找出对应的节点,最多只遍历了一半的节点,非常经典的一个链表遍历,写的很好!

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;
    }
}
5)linkBefore(E e, Node succ) 方法
void linkBefore(E e, Node<E> succ) {
        // assert succ != null;
        final Node<E> pred = succ.prev;
        final Node<E> newNode = new Node<>(pred, e, succ);
        succ.prev = newNode;
        if (pred == null)
            first = newNode;
        else
            pred.next = newNode;
        size++;
        modCount++;
    }

形参succ是原来index对应的节点,pred为原来succ的前一节点。
创建一新节点,左指针指向pred,右指针指向succ。
final Node newNode = new Node<>(pred, e, succ);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值