LinkedList源码解析

LinkedList源码解析

底层是双向链表

  • add()方法
  // 源码阅读.
    //1. LinkedList linkedList = new LinkedList();
       public LinkedList() {}
       
    //2. 这时 linkeList 的属性 first = null  last = null

    //3. 执行 添加
       public boolean add(E e) {
            linkLast(e); //把添加的数据挂在后面
            return true;
        }
         
     //4.将新的结点,加入到双向链表的最后
       void linkLast(E e) {
	       final Node<E> l = last;
	       final Node<E> newNode = new Node<>(l, e, null);
		   //第一次:newNode 此时 item = e  first = null  last = null
	       last = newNode;
	       if (l == null)
	           first = newNode;
	       else
	           l.next = newNode;
	       size++;
	       modCount++;
       }

第一次添加完成
第一次添加完成
第二次添加完成
第二次添加完成

  • remove() 方法
// 读源码 linkedList.remove(); // 这里默认删除的是第一个结点
    //1. 执行 removeFirst
      public E remove() {
          return removeFirst();
      }
    //2. 执行
      public E removeFirst() {
          final Node<E> f = first; // f 指向第一个节点
          if (f == null) //如果是空列表报异常
              throw new NoSuchElementException();
          return unlinkFirst(f); // 真正删除的是此方法
      }
    //3. 执行 unlinkFirst, 将 f 指向的双向链表的第一个结点拿掉
      private E unlinkFirst(Node<E> f) {
          // assert f == first && f != null;
          final E element = f.item;
          final Node<E> next = f.next;
          f.item = null;
          f.next = null; // help GC
          first = next;
          if (next == null)
              last = null;
          else
              next.prev = null;
          size--;
          modCount++;
          return element;
      }

删除的流程
删除一个节点的流程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值