zoukankan      html  css  js  c++  java
  • Java底层类和源码分析系列-LinkedList底层架构和源码分析

    几个要点

    LinkedList的底层数据结构是双向链表;
    LinkedList继承于AbstractSequentialList的双向链表,实现List接口,因此也可以对其进行队列操作,它也实现了Deque接口,所以LinkedList也可当做双端队列使用;
    LinkedList是非同步的;
    和 ArrayList 一样,LinkedList 也支持空值和重复值;
    LinkedList 存储元素的节点需要额外的空间存储前驱和后继的引用;
    LinkedList 在链表头部和尾部插入效率比较高,但在指定位置进行插入时,效率一般;
    LinkedList 的顺序读取效率很低,需要从链表头结点(或尾节点)向后查找,时间复杂度为 O(N);
    LinkedList 实现 List 接口,能对它进行队列操作。
    LinkedList 实现 Deque 接口,即能将LinkedList当作双端队列使用。
    LinkedList 实现了Cloneable接口,即覆盖了函数clone(),能克隆。
    LinkedList 实现java.io.Serializable接口,这意味着LinkedList支持序列化,能通过序列化去传输。

    常用方法

    LinkedList<String> dataList = new LinkedList<>(); // 创建 LinkedList
    dataList.add("test"); // 添加数据
    dataList.add(1, "test1"); // 指定位置,添加数据
    dataList.addFirst("first"); // 添加数据到头部
    dataList.addLast("last"); // 添加数据到尾部
    dataList.get(0); // 获取指定位置数据
    dataList.getFirst(); // 获取头部数据
    dataList.getLast(); // 获取尾部数据
    dataList.remove(1); // 移除指定位置的数据
    dataList.removeFirst(); // 移除头部数据
    dataList.removeLast(); // 移除尾部数据
    dataList.clear(); // 清空数据

    定义

    public class LinkedList<E>
        extends AbstractSequentialList<E>
        implements List<E>, Deque<E>, Cloneable, java.io.Serializable    

    核心数据结构

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

    成员属性

    transient int size = 0;
    
    transient Node<E> first;
    
    transient Node<E> last;

    构造方法

      public LinkedList() {
        }
    
        public LinkedList(Collection<? extends E> c) {
            this();
            addAll(c);
        }

    add

    /** 在链表尾部插入元素 */
    public boolean add(E e) {
        linkLast(e);
        return true;
    }
    
    /** 在链表指定位置插入元素 */
    public void add(int index, E element) {
        checkPositionIndex(index);
    
        // 判断 index 是不是链表尾部位置,如果是,直接将元素节点插入链表尾部即可
        if (index == size)
            linkLast(element);
        else
            linkBefore(element, node(index));
    }
    
    /** 将元素节点插入到链表尾部 */
    void linkLast(E e) {
        final Node<E> l = last;
        // 创建节点,并指定节点前驱为链表尾节点 last,后继引用为空
        final Node<E> newNode = new Node<>(l, e, null);
        // 将 last 引用指向新节点
        last = newNode;
        // 判断尾节点是否为空,为空表示当前链表还没有节点
        if (l == null)
            first = newNode;
        else
            l.next = newNode;    // 让原尾节点后继引用 next 指向新的尾节点
        size++;
        modCount++;
    }
    
    /** 将元素节点插入到 succ 之前的位置 */
    void linkBefore(E e, Node<E> succ) {
        // assert succ != null;
        final Node<E> pred = succ.prev;
        // 1. 初始化节点,并指明前驱和后继节点
        final Node<E> newNode = new Node<>(pred, e, succ);
        // 2. 将 succ 节点前驱引用 prev 指向新节点
        succ.prev = newNode;
        // 判断尾节点是否为空,为空表示当前链表还没有节点    
        if (pred == null)
            first = newNode;
        else
            pred.next = newNode;   // 3. succ 节点前驱的后继引用指向新节点
        size++;
        modCount++;
    }
    
    public boolean addAll(int index, Collection<? extends E> c) {
            // 检查index是否越界
            checkPositionIndex(index);
    
            Object[] a = c.toArray();
            int numNew = a.length;
            // 如果插入集合无数据,则直接返回
            if (numNew == 0)
                return false;
    
            // succ的前驱节点
            Node<E> pred, succ;
            // 如果index与size相同
            if (index == size) {
                // succ的前驱节点直接赋值为最后节点
                // succ赋值为null,因为index在链表最后
                succ = null;
                pred = last;
            } else {
                // 取出index上的节点
                succ = node(index);
                pred = succ.prev;
            }
            // 遍历插入集合
            for (Object o : a) {
                @SuppressWarnings("unchecked") E e = (E) o;
                // 创建新节点 前驱节点为succ的前驱节点,后续节点为null
                Node<E> newNode = new Node<>(pred, e, null);
                // succ的前驱节点为空,则表示succ为头,则重新赋值第一个结点
                if (pred == null)
                    first = newNode;
                else
                    // 构建双向链表
                    pred.next = newNode;
                // 将前驱节点移动到新节点上,继续循环
                pred = newNode;
            }
    
            // index位置上为空 赋值last节点为pred,因为通过上述的循环pred已经走到最后了
            if (succ == null) {
                last = pred;
            } else {
                // 构建双向链表
                // 从这里可以看出插入集合是在succ[index位置上的节点]之前
                pred.next = succ;
                succ.prev = pred;
            }
            // 元素总数更新
            size += numNew;
            // 修改次数自增
            modCount++;
            return true;
        }

    remove

    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;
    }
    
    public E remove(int index) {
        checkElementIndex(index);
        // 通过 node 方法定位节点,并调用 unlink 将节点从链表中移除
        return unlink(node(index));
    }
    
    /** 将某个节点从链表中移除 */
    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;
        
        // prev 为空,表明删除的是头节点
        if (prev == null) {
            first = next;
        } else {
            // 将 x 的前驱的后继指向 x 的后继
            prev.next = next;
            // 将 x 的前驱引用置空,断开与前驱的链接
            x.prev = null;
        }
    
        // next 为空,表明删除的是尾节点
        if (next == null) {
            last = prev;
        } else {
            // 将 x 的后继的前驱指向 x 的前驱
            next.prev = prev;
            // 将 x 的后继引用置空,断开与后继的链接
            x.next = null;
        }
    
        // 将 item 置空,方便 GC 回收
        x.item = null;
        size--;
        modCount++;
        return element;
    }

    unlink 方法的逻辑如下(假设删除的节点既不是头节点,也不是尾节点):

    将待删除节点 x 的前驱的后继指向 x 的后继
    将待删除节点 x 的前驱引用置空,断开与前驱的链接
    将待删除节点 x 的后继的前驱指向 x 的前驱
    将待删除节点 x 的后继引用置空,断开与后继的链接

    get

    public E get(int index) {
        checkElementIndex(index);
        return node(index).item;
    }
    
    Node<E> node(int index) {
        /*
         * 则从头节点开始查找,否则从尾节点查找
         * 查找位置 index 如果小于节点数量的一半,
         */    
        if (index < (size >> 1)) {
            Node<E> x = first;
            // 循环向后查找,直至 i == index
            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;
        }
    }

    比较 index 与节点数量 size/2 的大小,决定从头结点还是尾节点进行查找,这样可以将时间复杂度降为 O(N/2)

    peekpollpushpop的区别

    还具有堆栈的方法。

    //仅仅取首数据
        public E peek() {
            final Node<E> f = first;
            return (f == null) ? null : f.item;
        }
    
    //取首数据,还要删除
            public E poll() {
            final Node<E> f = first;
            return (f == null) ? null : unlinkFirst(f);
        }
    
    //存入栈首
        public void push(E e) {
            addFirst(e);
        }
        public boolean offer(E e) {
            return add(e);
        }
    //和poll一样
        public E pop() {
            return removeFirst();
        }
  • 相关阅读:
    hdu4472-Count
    Codeforces Beta Round #55 (Div. 2)
    优化素数表
    Codeforces Beta Round #49 (Div. 2)-D. Physical Education
    Codeforces Beta Round #49 (Div. 2)-C. Little Frog
    一些不知道的函数
    kmp算法详解
    STL之accumulate用法小结
    STL——list学习笔记
    maven打war包包含源文件-eclipse
  • 原文地址:https://www.cnblogs.com/starcrm/p/12697606.html
Copyright © 2011-2022 走看看