每天半小时源码 - LinkedList

LinkedList

模拟指针

    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;
        }
    }

size

/*
 * 记录LinkedList的 长度
 */
transient int size = 0;

first

    /**
     * 指向第一个节点的指针
     * Invariant: (first == null && last == null) ||
     *            (first.prev == null && first.item != null)
     */
    transient Node<E> first;

last

    /**
     * 指向最后一个节点的指针
     * Invariant: (first == null && last == null) ||
     *            (last.next == null && last.item != null)
     */
    transient Node<E> last;

构造方法

LinkedList()


    /**
     * 构造一个空列表
     */
    public LinkedList() {
    }

LinkedList(Collection

    /**
     * 构造包含指定集合元素的列表,按集合迭代器返回的顺序.
     * @throws 当如果添加的集合为空的时候 那么会出现空指针异常
     */
    public LinkedList(Collection<? extends E> c) {
        this();
        addAll(c);
    }
    //示例 ------------------------------不在源代码中的一部分
    public static void main(String[] args) {
        LinkedList<String> list = new LinkedList<>();
        List<String> demo = null;
        list.add("a");
        // 当添加的时候 会出现空指针异常
        list.addAll(demo);
        list.forEach(item -> System.out.println(item));
    }

外部方法

E getFirst()

    /**
     * 返回集合中的第一个元素
     *
     * @return the first element in this list
     * @throws 如果头指针为空 那么抛出异常
     */
    public E getFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return f.item;
    }

E getLast()

    /**
     * 返回集合中的最后一个元素
     *
     * @return the last element in this list
     * @throws 如果最后一个元素为空, 那么抛出异常
     */
    public E getLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return l.item;
    }

E removeFirst()

    /**
     * 删除掉 第一个元素
     * @return the first element from this list
     * @throws NoSuchElementException if this list is empty
     */
    public E removeFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return unlinkFirst(f);
    }

E removeLast()

    /**
     * 删除集合中的最后一个元素
     *
     * @return the last element from this list
     * @throws NoSuchElementException if this list is empty
     */
    public E removeLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return unlinkLast(l);
    }

void addFirst()

    /**
     * 添加指定的元素 到集合的开头
     * @param e the element to add
     */
    public void addFirst(E e) {
        linkFirst(e);
    }

void addLast

    /**
     * 将指定的元素添加到列表的尾部.

     * @param e the element to add
     */
    public void addLast(E e) {
        linkLast(e);
    }

contains(Object o)

    /**
     * 判断指定的元素是否存在于集合中
     * @param o element whose presence in this list is to be tested
     * @return {@code true} if this list contains the specified element
     */
    public boolean contains(Object o) {
        return indexOf(o) != -1;
    }

int size()

    /**
     * 返回集合中的长度
     * @return the number of elements in this list
     */
    public int size() {
        return size;
    }

boolean add(E e)

    /**
     * 为集合中 添加指定的元素 实际上 跟 addLast 放方法相似
     * @param e element to be appended to this list
     * @return {@code true} (as specified by {@link Collection#add})
     */
    public boolean add(E e) {
        linkLast(e);
        return true;
    }

boolean remove(E e)

    /**
     * 如果该元素存在, 那么就移除,只删除该元素首次出现的位置
     * 如果该列表不包含元素,则它不变。
     */
    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;
    }

addAll(Collection< ? extends E > c)

    /**
     * 将指定集合中的所有元素追加到此列表的末尾, 按照指定集合的迭代器返回的顺序.  
       如果在操作正在进行时修改了指定的集合,则此操作的行为是不确定的。
       (请注意,如果指定的集合是此列表,并且它是非空的,则会发生这种情况)
     *
     * @param c collection containing elements to be added to this list
     * @return {@code true} if this list changed as a result of the call
     * @throws NullPointerException if the specified collection is null
     */
    public boolean addAll(Collection<? extends E> c) {
        // size 该集合的长度  默认是添加到集合的末端
        return addAll(size, c);
    }

addAll(int index, Collection

   /**
     * 从指定位置开始,将指定集合中的所有元素插入此列表。
     * 将当前位置的元素(如果有)和任何后续元素向右移动(增加其索引).  
     * 新元素将按照指定集合的迭代器返回的顺序出现在列表中.
     * @param index 指定集合插入元素的位置
     * @param c collection containing elements to be added to this list
     * @return {@code true} if this list changed as a result of the call
     * @throws IndexOutOfBoundsException {@inheritDoc}
     * @throws NullPointerException if the specified collection is null
     */
    public boolean addAll(int index, Collection<? extends E> c) {
        // 检查索引是否 超出了 集合的长度 超过了 就抛出 IndexOutOfBoundsException 异常
        checkPositionIndex(index);
        // 将传入的集合转换为一个数组
        Object[] a = c.toArray();
        // 得到传入数组的长度
        int numNew = a.length;
        // 如果长度为0  代表 增加的集合为空, 直接返回
        if (numNew == 0)
            return false;
        // 定义两个节点
        Node<E> pred, succ;
        // 判断传入的索引 是否等于链表的长度 , 如果是等于链长  说明是直接从末尾添加
        if (index == size) {
            succ = null;
            pred = last;
        } else {
            // 将指定位置索引的结点赋值给 succ , 然后将指定位置结点的以一个结点赋值给 pred
            succ = node(index);
            pred = succ.prev;
        }
        // 遍历 传入的对象
        for (Object o : a) {
            @SuppressWarnings("unchecked") 
            //转换对象类型
            E e = (E) o;
            // 初始化结点  并标记上一个结点  上一个结点是 在索引位置的上一个结点
            Node<E> newNode = new Node<>(pred, e, null);
            // 如果 头结点为空的话, 表明索引位置在第一位, 应该将新头结点, 赋值为当前结点
            if (pred == null)
                first = newNode;
            else
                // 正常情况下, 就直接将 结点 添加到 pred 结点之后
                pred.next = newNode;
            pred = newNode;
        }// 遍历完后, 在传入的集合中 所有的元素, 都添加到了 指定索引位置, 接下来就是 索引后面位置的结点

        // 判断索引后面的succ 结点是否为空, 如果为空, 就代表最开始的时候就是从, 最后的结点开始添加的
        // 这样就可以直接, 将 处理完添加集合的pred 结点 设置为末节点
        if (succ == null) {
            last = pred;
        } else {
            // 如果不是 就直接将 结点之间 拼接起来
            pred.next = succ;
            succ.prev = pred;
        }

        size += numNew;
        modCount++;
        return true;
    }

void clear()

    /**
     * 清除掉 链表中的所有元素
     */
    public void clear() {
        // Clearing all of the links between nodes is "unnecessary", but:
        // - helps a generational GC if the discarded nodes inhabit
        //   more than one generation
        // - is sure to free memory even if there is a reachable Iterator
        for (Node<E> x = first; x != null; ) {
            Node<E> next = x.next;
            x.item = null;
            x.next = null;
            x.prev = null;
            x = next;
        }
        first = last = null;
        size = 0;
        modCount++;
    }

E get(int index)

    /**
     * 返回在链表指定位置的元素
     */
    public E get(int index) {
        // 判断元素是否超出 链表的长度 超过就 抛出异常
        checkElementIndex(index);
        return node(index).item;
    }

E set(int index, E element)

/**
 * 将链表中指定位置的元素, 替换为指定元素
 */
public E set(int index, E element) {
    // 判断元素是否超出 链表的长度 超过就 抛出异常
    checkElementIndex(index);
    // 得到以前指定位置的结点
    Node<E> x = node(index);
    // 得到item
    E oldVal = x.item;
    // 改变值
    x.item = element;
    // return
    return oldVal;
}

void add(int index, E element)


    /**
     * 在指定的位置添加元素
     *
     * @param index index at which the specified element is to be inserted
     * @param element element to be inserted
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public void add(int index, E element) {
        // 判断元素是否超出 链表的长度 超过就 抛出异常
        checkPositionIndex(index);

        if (index == size)
            linkLast(element);
        else
            linkBefore(element, node(index));
    }

E remove(int index)

    /**
     * 删除指定位置的元素
     *
     * @param index the index of the element to be removed
     * @return the element previously at the specified position
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E remove(int index) {
        // 判断元素是否超出 链表的长度 超过就 抛出异常
        checkElementIndex(index);
        return unlink(node(index));
    }

int lastIndexOf(Object o)

    /**
     * Returns the index of the last occurrence of the specified element
     * in this list, or -1 if this list does not contain the element.
     * More formally, returns the highest index {@code i} such that
     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
     * or -1 if there is no such index.
     *
     * @param o element to search for
     * @return the index of the last occurrence of the specified element in
     *         this list, or -1 if this list does not contain the element
     */
    public int lastIndexOf(Object o) {
        int index = size;
        if (o == null) {
            for (Node<E> x = last; x != null; x = x.prev) {
                index--;
                if (x.item == null)
                    return index;
            }
        } else {
            for (Node<E> x = last; x != null; x = x.prev) {
                index--;
                if (o.equals(x.item))
                    return index;
            }
        }
        return -1;
    }

私有方法

void linkFirst(E e)

    /**
     * Links e 作为第一个元素
     */
    private void linkFirst(E e) {
        // 得到以前头结点的元素
        final Node<E> f = first;
        // 定义一个新的头结点
        final Node<E> newNode = new Node<>(null, e, f);
        // 将定义的新的头结点赋值给first
        first = newNode;
        // 判断以前的头结点是否为空  如果为空 那么现在的头结点和尾结点都应该是 新定义的元素 newNode 
        if (f == null)
            last = newNode;
        // 如果不为空 就直接将 f的 前一个结点的元素设置为新添加的结点newNode
        else
            f.prev = newNode;
        // 添加完之后  将元素的长度 ++
        size++;
        modCount++;
    }

void linkLast(E e)

    /**
     * Links e 最为最后一个元素
     */
    void linkLast(E e) {
        final Node<E> l = last;
        final Node<E> newNode = new Node<>(l, e, null);
        last = newNode;
        if (l == null)
            first = newNode;
        else
            l.next = newNode;
        size++;
        modCount++;
    }

void linkBefore(E e, Node succ)

    /**
     * Inserts element e before non-null 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++;
    }

E unlinkFirst(Node f)

    /**
     * 删除 传入的结点
     */
    private E unlinkFirst(Node<E> f) {
        // 获取得到头指针的内容
        final E element = f.item;
        // 将指针的next 域 保存下来
        final Node<E> next = f.next;
        // 将传入的结点的内容和 next 赋值为空
        f.item = null;
        f.next = null; // help GC
        //将first 结点指向已经删除的结点的下一个结点
        first = next;
        if (next == null)
            last = null;
        else
            next.prev = null;
        size--;
        modCount++;
        return element;
    }

E unlinkLast(Node 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;
        l.prev = null; // help GC
        last = prev;
        if (prev == null)
            first = null;
        else
            prev.next = null;
        size--;
        modCount++;
        return element;
    }

E unlink(Node x)

    /**
     * 删除传入的结点
     */
    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 {
            // 按照正常流程 如果前一个结点  不为空 存在数据, 那么就应该讲 前一个结点的next 等于 当前结点的next  也就是 prev.next = next , 并且将当前结点的 前一个结点置空
            prev.next = next;
            x.prev = null;
        }
        // 判断 当前节点的 指针域是否为空, 如果为空 那么表明当前结点为 last 结点, 那么删除当前结点, 就应该让 当前节点的上一个结点成为 last 结点, last = prev;
        if (next == null) {
            last = prev;
        } else {
            // 正常情况下, 将 当前结点的下一个结点的上一个结点指向 当前节点的上一个结点 并将当前节点的next 赋值为空
            next.prev = prev;
            x.next = null;
        }
        // 将内容赋值为空
        x.item = null;
        size--;
        modCount++;
        return element;
    }

Node node(int index)

    /**
     * 返回指定元素索引处的(非null)节点
     */
    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;
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值