[Java集合源码]LinkedList源码

jdk版本:1.8

参考:
- https://blog.csdn.net/qq_19431333/article/details/54572876
- https://blog.csdn.net/ns_code/article/details/35787253

  • LinkedList是基于双向链表实现的,除了可以当做链表来操作外,它还可以当做栈、队列和双端队列来使用。
  • LinkedList同样是非线程安全的,只在单线程下适合使用。
  • 基于链表实现,没有长度限制
public class LinkedList<E>
        extends AbstractSequentialList<E>
        implements List<E>, Deque<E>, Cloneable, java.io.Serializable
    //LinkedList是一个实现了List接口和Deque接口的双端链表
{
    //size表示当前链表中的数据个数
    transient int size = 0;

    //指向第一个节点的指针
    transient Node<E> first;

    //指向最后一个节点的指针
    transient Node<E> last;


    //默认为空的构造函数
    public LinkedList() {
    }


    //构造一个包含指定集合的链表
    public LinkedList(Collection<? extends E> c) {
        this();
        addAll(c);
    }

    /**
     * Links e as first element.
     */
    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;
        size++;
        modCount++;
    }

    /**
     * Links e as last element.
     */
    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++;
    }

    /**
     * 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++;
    }

    /**
     * Unlinks non-null first node 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;
    }

    /**
     * Unlinks non-null last 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;
    }

    /**
     * Unlinks non-null 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 {
            prev.next = next;
            x.prev = null;
        }

        if (next == null) {
            last = prev;
        } else {
            next.prev = prev;
            x.next = null;
        }

        x.item = null;
        size--;
        modCount++;
        return element;
    }

    //返回链表中第一个元素
    public E getFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return f.item;
    }

    //返回链表最后一个元素
    public E getLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return l.item;
    }

    //移除第一个元素并返回该元素
    public E removeFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return unlinkFirst(f);//具体的实现操作
    }

    //移除最后一个元素并返回
    public E removeLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return unlinkLast(l);//具体的实现操作
    }


    //在链表首部增加元素
    public void addFirst(E e) {
        linkFirst(e);//具体的实现操作
    }

    //在链表尾部增加元素
    public void addLast(E e) {
        linkLast(e);//具体的实现操作
    }

    //链表中是否包含该元素
    public boolean contains(Object o) {
        return indexOf(o) != -1;
    }

    //返回链表中的元素个数
    public int size() {
        return size;
    }


    //增加元素,是增加到链表尾部的
    public boolean add(E e) {
        linkLast(e);
        return true;
    }


    //移除链表中第一次出现的元素,如果链表不包含该元素则不做修改
    //可以看出链表也是支持null
    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;
    }

     //将指定集合中的所有元素追加到链表尾部。
    //实际上,是从双向链表的末尾开始,将“集合(c)”添加到双向链表中。
    public boolean addAll(Collection<? extends E> c) {
        return addAll(size, c);
    }

    //从双向链表的index开始,将“集合(c)”添加到双向链表中。
    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;

        Node<E> pred, succ;//得到插入位置的前驱节点和后继节点
        if (index == size) {//如果插入位置为尾部,前驱节点为last,后继节点为null
            succ = null;
            pred = last;
        } else {//否则,调用node()方法得到后继节点,再得到前驱节点
            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.next = newNode;
            pred = newNode;
        }
        //如果插入位置在尾部,重置last节点
        if (succ == null) {
            last = pred;
        } else {//否则,将插入的链表与先前链表连接起来
            pred.next = succ;
            succ.prev = pred;
        }

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

    //移除链表中所有元素
    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++;
    }


    // Positional Access Operations


    //根据指定索引返回数据,如果索引越界,那么会抛出异常
    public E get(int index) {
        checkElementIndex(index);//检查索引
        return node(index).item;
    }


    //修改指定位置的元素数据并返回之前的元素数据
    public E set(int index, E element) {
        checkElementIndex(index);
        Node<E> x = node(index);
        E oldVal = x.item;
        x.item = element;
        return oldVal;
    }


    //在指定位置增加元素
    public void add(int index, E element) {
        checkPositionIndex(index);

        if (index == size)//如果指定位置==链表大小则直接增加在链表尾部
            linkLast(element);
        else
            linkBefore(element, node(index));
    }


    //根据索引位置移除元素,并返回该元素。移除元素那么
    public E remove(int index) {
        checkElementIndex(index);
        return unlink(node(index));
    }

    /**
     * Tells if the argument is the index of an existing element.
     */
    private boolean isElementIndex(int index) {
        return index >= 0 && index < size;
    }

    /**
     * Tells if the argument is the index of a valid position for an
     * iterator or an add operation.
     */
    private boolean isPositionIndex(int index) {
        return index >= 0 && index <= size;
    }

    /**
     * Constructs an IndexOutOfBoundsException detail message.
     * Of the many possible refactorings of the error handling code,
     * this "outlining" performs best with both server and client VMs.
     */
    private String outOfBoundsMsg(int index) {
        return "Index: "+index+", Size: "+size;
    }

    private void checkElementIndex(int index) {
        if (!isElementIndex(index))
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    private void checkPositionIndex(int index) {
        if (!isPositionIndex(index))
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    /**
     * Returns the (non-null) Node at the specified element 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;
        }
    }

    // Search Operations


    //返回对象第一次出现的位置下标,分null和非null处理,如果没有则返回-1
    public int indexOf(Object o) {
        int index = 0;
        if (o == null) {
            for (Node<E> x = first; x != null; x = x.next) {
                if (x.item == null)
                    return index;
                index++;
            }
        } else {
            for (Node<E> x = first; x != null; x = x.next) {
                if (o.equals(x.item))
                    return index;
                index++;
            }
        }
        return -1;
    }

    //从后向前查找,返回“值为对象(o)的节点第一次出现对应的索引”
    //不存在就返回-1
    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;
    }

    // Queue operations.


    //返回但不删除此列表的头(第一个元素)。
    public E peek() {
        final Node<E> f = first;
        return (f == null) ? null : f.item;
    }


    //返回但不删除此列表的头(第一个元素)。
    public E element() {
        return getFirst();
    }

    //返回并删除此列表的头(第一个元素)
    public E poll() {
        final Node<E> f = first;
        return (f == null) ? null : unlinkFirst(f);
    }

    //返回并删除此列表的头(第一个元素)。
    public E remove() {
        return removeFirst();
    }


    //offer(E e)方法用于将数据添加到链表尾部,其内部调用了add(E e)方法
    public boolean offer(E e) {
        return add(e);
    }

    // Deque operations LinkedList可以当做队列来使用
    //offerFirst()方法用于将数据插入链表头部,
    public boolean offerFirst(E e) {
        addFirst(e);
        return true;
    }


    //offerLast()方法用于将数据插入链表尾部,
    public boolean offerLast(E e) {
        addLast(e);
        return true;
    }

    //返回链表头元素,但是不移除
    public E peekFirst() {
        final Node<E> f = first;
        return (f == null) ? null : f.item;
    }
    //返回链表尾元素,但是不移除
    public E peekLast() {
        final Node<E> l = last;
        return (l == null) ? null : l.item;
    }

    //返回链表头元素,并移除
    public E pollFirst() {
        final Node<E> f = first;
        return (f == null) ? null : unlinkFirst(f);
    }

    返回链表尾元素,并移除
    public E pollLast() {
        final Node<E> l = last;
        return (l == null) ? null : unlinkLast(l);
    }


    //将元素推送到由此列表表示的堆栈上。
    //换句话说就是将元素增加在链表头部
    public void push(E e) {
        addFirst(e);
    }


    //从此列表表示的堆栈中弹出一个元素。 
    //换句话说,移除并返回链表的头结点元素
    public E pop() {
        return removeFirst();
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值