LinkedList源码解析

LinkedList 源码解析

JDK位置:java.util.LinkedList

数据结构:双向链表 (查找只需检查一半,从头或从尾开始搜索)

特点:增删快,查找慢(它的特点刚好和ArrayList 相反)

适用场景:适用于对集合中的元素做大量的增删操作的场景 。

链表(linked list) 是由一个个的node结点组成,每个node结点中包含两项数据:

1.指针域(单链表的指针域是指存储指向下一个node节点对象的引用(Java中为引用(Java中引用和指针并不是同一物,但是在初入学习中可以近似看做就是指针),C/C++中为指针))

2.数据域(数据存储的地方,数据的载体)

双向链表则一个节点包含三项:(指针域包含两个,我称为前指针和后指针)指向上一个节点指针、指向下一个节点指针、数据域。

注: “结” 和“节”都是一会事儿,出现歧义本就是node翻译的问题,有人称“结”,有人称“节”,这都是存在的,不过这都不重要,只需要清楚说的是同一回事儿。所以,在本文中我将链表的前和尾结点用“结”表示,便于我在源码中更清楚的理解,中间的节点都是用“节”称呼,总之这个两都是指的是node。

前继节点:当前节点的前指针指向的上一个节点

后继节点:当前节点的后指针指向的下一个节点

1.构造器

	// 无参构造器(不传入一个指定列表)
	public LinkedList() {
    }
	// 有参构造器(传入一个指定列表)
    public LinkedList(Collection<? extends E> c) {
        this();
        addAll(c); // 添加方法
    }

2.成员变量

 	transient int size = 0; // 链表的长度,节点个数
    /**
     * Pointer to first node.
     * Invariant: (first == null && last == null) ||
     *            (first.prev == null && first.item != null)
     */
    transient Node<E> first; // 记录头结点(前指针为空)
    /**
     * Pointer to last node.
     * Invariant: (first == null && last == null) ||
     *            (last.next == null && last.item != null)
     */
    transient Node<E> last; // 记录尾结点(后指针点为空)

注: 每一对链表进行修改时(增加、删除、替换等使节点元素发生改变)都要对头结点和尾结点进行更新(也就是该方法中都要考虑是否更改头尾结点),否则在进行链表查询和其他的修改操作时将会与预期结果相悖。

当尾结点lastnull时,意味着firstnull。

3.节点类

	// 节点声明为私有内部类
	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;
        }
    }

4.插入方法

	/** Appends the specified element to the end of this list. */
	// 默认在尾结点后添加;E是泛型,e作为数据对象参数传入
	public boolean add(E e) { // 添加成功返回true
        linkLast(e);
        return true;
    }
	/** Links e as last element. */
	// 在链表末尾添加一个节点,使该节点成为新的尾结点。
    void linkLast(E e) {
        // 将旧的尾结点保存到 l 中,并使 l 的值不能变( l 是Node引用类型,保存的是last的引用),并将其作为即将创建的新节点的前继节点
        final Node<E> l = last; 
        // 创建一个新节点,并将旧尾节点的地址值(地址值不太准确,引用),也就是 l 中保存的引用作为前指针、e作为数据,设后指针为null,创建一个Node对象
        final Node<E> newNode = new Node<>(l, e, null);
        // 更新链表的尾结点
        last = newNode;
        /* 判断链表中是否存在元素节点,如果 l 为null则意味则当前链表没有节点,新创建的节点就是第一个节点,并使newNode作为头结点。此处不需要单独设头结点的前指针为null,在当 l 为空时,创键newNode对象时调用的构造器中 l = null,也就是该节点的前指针为null。否则newNode的前继节点的后指针指向newNode。
        */
        if (l == null)
            first = newNode;
        else
            l.next = newNode;
        size++; // 节点创建成功后,链表长度 + 1
        // 该参数表示链表的操作次数;单纯就链表来说并不重要,它是继承的AbstractList,与迭代器相关
        modCount++; 
    }

 /** Inserts the specified element at the specified position in this list.*/
	// 指定元素位置添加节点
    public void add(int index, E element) {
        // 检查索引是否越界
        checkPositionIndex(index);

        /* 如果index == size,说明是在链表的末尾处添加一个节点(也就是添加为结点)
           如果index != size,说明是在链表的中间添加一个节点,调用linkBefore,传入参数即可
        */
        if (index == size)
            linkLast(element);
        else
            linkBefore(element, node(index));
    }

 /** Inserts element e before non-null Node succ.
 	 存在元素节点succ,且在succ(此节点可以为任意节点-头结点、中间节点、尾结点)之前插入元素节点(也就是在链表的中间或最前面插入元素节点)
 	 succ就是index索引指向的节点
     */
    void linkBefore(E e, Node<E> succ) {
        // assert succ != null;
        // 将succ的前指针的引用保存在一个Node类型pred中(该pred指向succ的前继节点)
        final Node<E> pred = succ.prev;
        // 创建新节点,该节点的前指针指向succ的前继节点,数据域保存传入的数据,后指针保存succ的地址引用(指向succ)
        final Node<E> newNode = new Node<>(pred, e, succ);
        // 并将succ的前指针指向创建的新节点,使新节点成为succ新的前继节点
        succ.prev = newNode;
        // 判断succ的是否是头结点,如果是,那么插入的新节点将取代succ成为新的头结点;
        if (pred == null)
            first = newNode;
        else
            // 如果不是,那么原先succ的前继节点就需要指向创建的新节点
            pred.next = newNode;
        size++;
        modCount++;
    }

5.检查索引是否越界

// 定义为私有,只允许当前类调用;如果越界直接抛出IndexOutOfBoundsException异常
private void checkPositionIndex(int index) {
        if (!isPositionIndex(index))
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
// 判断索引值是否在有效范围0~size(链表长度)内
private boolean isPositionIndex(int index) {
        return index >= 0 && index <= size;
    }

6.删除方法

/**
     * Retrieves and removes the head (first element) of this list.
     * 默认删除头结点
     */
    public E remove() {
        return removeFirst();
    }

/**
     * Removes the element at the specified position in this list.  Shifts any
     * subsequent elements to the left (subtracts one from their indices).
     * Returns the element that was removed from the list.
     * 根据索引删除节点
     */
    public E remove(int index) {
        checkElementIndex(index);
        return unlink(node(index));
    }

 /**
     * Removes the first occurrence of the specified element from this list,
     * if it is present.  If this list does not contain the element, it is
     * unchanged.  More formally, removes the element with the lowest index
     * {@code i} such that
     * 根据对象删除
     */
    public boolean remove(Object o) {
        // 对象为空(null)只能用“==”,不能用equals()
        if (o == null) {
            // 从第一个链表开始循环查找(通过尾结点的后指针为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;
    }

/**
     * Removes and returns the first element from this list.
     * 删除头结点并返回
     */
    public E removeFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        // 保存的节点不为空则调用unlinkFirst()
        return unlinkFirst(f);
    }

    /**
     * Removes and returns the last element from this list.
     * 删除尾结点并返回
     */
    public E removeLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return unlinkLast(l);
    }

/** Unlinks non-null node x.
	将一个非空节点 x 断开链表(删除节点)
     */
    E unlink(Node<E> x) {
        // assert x != null;
        final E element = x.item; // 将该节点的数据保存在element中
        final Node<E> next = x.next; // 将该节点的后指针保存在next中
        final Node<E> prev = x.prev; // 将该节点的前指针保存在prev中

        // 判断 x 节点是否是头结点,如果是,则将 x 的后继节点设置为头结点;如果不是,则将 x 的前继节点(prev)中的后指针(prev.next)指向 x 的后继节点(next)。并将 x 的前指针设为null
        if (prev == null) {
            first = next;
            // next.prev = null; // (源码中是没有的,再手敲的时候遇见了该问题)这里逻辑上是可以不用加上 x 的后继节点的前指针变为null值。结合两个if-else来思考;一、如果prev==null,那么x它就是头结点,就不是尾结点,所以第二个if-else 会直接执行else ,也就意味着next.prev = null(此时prev为null),二、如果next==null,那么x它就是尾结点,不是头结点,所以第一个if-else 会直接执行else ,也就意味着prec.next = null(此时next为null) 三、x 即是头又是尾结点,意味着链表中只有一个节点 x ,prev,next都等于null,只需更新头尾结点
            // 所以从源码中,可以学到很多东西,能够学习大佬的逻辑思维,学习如何将程序简单化,程序的上下部分都是紧密相关的
        } else {
            prev.next = next;
            x.prev = null;
        }

        // 判断 x 节点是否是尾结点,如果是,则将 x 的前继节点设置为尾结点;如果不是,则将 x 的后继节点(next)中的前指针(next.prev)指向 x 的前继节点(next)。并将 x 的后指针设为null
        if (next == null) {
            last = prev;
        } else {
            next.prev = prev;
            x.next = null;
        }

        // 请空 x 节点的数据域
        x.item = null;
        // 链表长度 - 1
        size--;
        modCount++;
        // 返回节点 x 中的数据对象
        return element;
    }
/**
     * Unlinks non-null first node f.
     * 删除非空头结点,返回数据e
     */
    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 的后指针设为null,变为独立的对象,能加快GC的清理
        f.next = null; // help GC
        // 将第二个节点变为头结点
        first = next;
        // 判断链表中是否还有其他节点元素,如果没有则链表为空,将尾结点设为空(已经暗含将头结点设为空);否则将新的头结点的头指针指向空
        if (next == null)
            last = null; // 更新尾结点
        else
            next.prev = null;
        // 删除链表长度 - 1
        size--;
        modCount++;
        // 返回删除节点的数据域
        return element;
    }
/**
     * Unlinks non-null last node l.
     * 删除尾结点 l 
     */
    private E unlinkLast(Node<E> l) {
        // assert l == last && l != null;
        
        // 将原先的尾结点数据域和指针域的数据分别进行保存
        final E element = l.item;
        final Node<E> prev = l.prev;
        l.item = null;
        // 将节点 f 的后指针设为null,变为独立的对象,能加快GC的清理
        l.prev = null; // help GC
        // 将倒数第二个节点设为尾结点
        last = prev;
        // 判断原节点中是否还有其他节点元素。prev == null 意味着链表只有一个节点,删除该节点后,头结点就为空,否则原尾结点的前继节点的后指针指向空。
        if (prev == null)
            first = null;
        else
            prev.next = null;
        size--;
        modCount++;
        return element;
    }

7.根据索引查找元素节点

/** Returns the (non-null) Node at the specified element index. 
	根据index索引查找元素节点,返回一个非空节点x
*/
    Node<E> node(int index) {
        // assert isElementIndex(index);

        // 双向链表,只需查找链表长度的一半(size/2)
        // 如果index小于size/2 则从链表头部开始找,否则从链表尾部开始找
        if (index < (size >> 1)) {
            // 将头结点复制给一个创建的临时节点x
            Node<E> x = first;
            // 顺着指针域向后搜索,并将每一节点的后指针赋值给x节点(即最后 x 就是指向位于index节点的引用)。所以遍历时只能遍历到index的前继节点
            for (int i = 0; i < index; i++)
                x = x.next;
            return x;
        } else {
             // 将尾结点复制给一个创建的临时节点x
            Node<E> x = last;
            // 顺着指针域向前搜索,并将每一节点的前指针赋值给x节点(即最后 x 就是指向位于index节点的引用)。所以遍历时只能遍历到index的前后继节点
            for (int i = size - 1; i > index; i--)
                x = x.prev;
            return x;
        }
    }

8.查找方法

/**
     * Returns the element at the specified position in this list.
     * 根据索引查找节点元素
     */
    public E get(int index) {
        checkElementIndex(index);
        return node(index).item;
    }

/**
     * Returns the first element in this list.
     * 查询头结点元素
     */
    public E getFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return f.item;
    }

    /**
     * Returns the last element in this list.
     * 查询尾结点元素
     */
    public E getLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return l.item;
    }

总结

以上便是我最近在学习Java的链表的过程中,去扒的JDK1.8的源码,我不太清楚有没有细节上的变化,我想肯定不会有大的改动。链表的核心原理在这里都有体现,之里只有LinkedList的一些常用方法,其中还有很多不太常见的方法并没有去扒一扒,有兴趣的小伙伴可以自行去看看。在扒了源码后,在自己去模仿着写一个,更加的加深了我的理解,扒源码的过程中一些不太理解和疑惑的地方,在自己写的时候慢慢的解开了,受益颇丰。我建议看完源码后也去写写。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值