LinkedList源码解读,基于java1.8,转载请注明出处,谢谢

/*
 * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 */

package java.util;

import java.util.*;
import java.util.function.Consumer;

/**
 * 赵泉伟原创,转载请注明出处
 * @param <E>
 */

public class LinkedList<E>
        extends AbstractSequentialList<E>
        implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
    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;//链表的最后一个元素

    /**
     * Constructs an empty list.
     */
    public LinkedList() {//无惨构造方法
    }

    /**
     * Constructs a list containing the elements of the specified
     * collection, in the order they are returned by the collection's
     * iterator.
     *
     * @param  c the collection whose elements are to be placed into this list
     * @throws NullPointerException if the specified collection is null
     */
    public LinkedList(Collection<? extends E> c) {//有参构造方法
        this();//调用无参构造方法
        addAll(c);//调用addAll方法传入Collection对象
    }

    /**
     * Links e as first element.
     */
    private void linkFirst(E e) {//往头部新增一个节点
        final Node<E> f = first;//获取头部
        final Node<E> newNode = new Node<>(null, e, f);//构造node对象
        first = newNode;//将新增的节点作为头部
        if (f == null)//如果头部为空,则代表是空list
            last = newNode;//同时将新增的节点作为尾部
        else//否则
            f.prev = newNode;//将新节点作为原头部的prev
        size++;//list长度自增
        modCount++;//修改次数自增
    }

    /**
     * Links e as last element.
     */
    void linkLast(E e) {往尾部新增一个节点
        final Node<E> l = last;//获取尾部
        final Node<E> newNode = new Node<>(l, e, null);//构造node对象
        last = newNode;//将新增的节点作为尾部
        if (l == null)//如果尾部为空则代表链表为空
            first = newNode;//同时将新增的节点作为头部
        else//否则
            l.next = newNode;//将新节点作为原尾部的next
        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;//将原节点位置对象的prev取出保存
        final Node<E> newNode = new Node<>(pred, e, succ);//构造对象
        succ.prev = newNode;//将新节点作为旧节点对象的prev,与其建立连接
        if (pred == null)//如果pred为空则代表为新增头部
            first = newNode;//同时将新增节点作为头部
        else//否则
            pred.next = newNode;//将新节点作为原来pred的next,即替换原来的next对象
        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;//获取当前节点的next节点保存起来
        f.item = null;//将当前的元素值置为空
        f.next = null; // help GC 将当前节点的next属性置空
        first = next;//将原头部的next作为头部
        if (next == null)//如果next为空,则代表链表已经为空
            last = null;//同时将last置空
        else//否则
            next.prev = null;//将新头部的prev置为空
        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;//获取当前节点的prev节点保存起来
        l.item = null;//将当前的元素值置为空
        l.prev = null; // help GC将当前节点的prev属性置空
        last = prev;//将原尾部的prev作为尾部
        if (prev == null)//如果prev为空,则代表链表已经为空
            first = null;//同时将first置空
        else//否则
            prev.next = null;//将新尾部的next置为空
        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;//指定节点的next保存起来
        final Node<E> prev = x.prev;//指定节点的元素prev保存起来

        if (prev == null) {//若prev为空则代表删除的为头部
            first = next;//将next置为新的first
        } else {//否则
            prev.next = next;//将prev的next由原来的x置为x的next
            x.prev = null;//将x的prev置为空
        }

        if (next == null) {//若next为空则代表是尾部
            last = prev;//将prev置为新的last
        } else {//否则
            next.prev = prev;将next的prev由原来的x置为prev
            x.next = null;//将x的next置为空
        }

        x.item = null;//将元素置为空
        size--;//链表长度自减
        modCount++;//修改次数自增
        return element;//返回删除的元素
    }

    /**
     * Returns the first element in this list.
     *
     * @return the first element in this list
     * @throws NoSuchElementException if this list is empty
     */
    public E getFirst() {//返回头部第一个元素,如果头部为空则抛出异常
        final Node<E> f = first;//获取头部
        if (f == null)//如果为空抛异常
            throw new NoSuchElementException();
        return f.item;//返回元素
    }

    /**
     * Returns the last element in this list.
     *
     * @return the last element in this list
     * @throws NoSuchElementException if this list is empty
     */
    public E getLast() {//获取最后一个元素
        final Node<E> l = last;//获取尾部
        if (l == null)//如果为空抛出异常
            throw new NoSuchElementException();
        return l.item;//返回元素
    }

    /**
     * Removes and returns the first element from this list.
     *
     * @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);//执行删除节点并返回
    }

    /**
     * Removes and returns the last element from this list.
     *
     * @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);//执行移除最后一个节点的方法并返回
    }

    /**
     * Inserts the specified element at the beginning of this list.
     *
     * @param e the element to add
     */
    public void addFirst(E e) {//往头部增加指定元素的节点
        linkFirst(e);//执行往头部增加节点的方法
    }

    /**
     * Appends the specified element to the end of this list.
     *
     * <p>This method is equivalent to {@link #add}.
     *
     * @param e the element to add
     */
    public void addLast(E e) {//往尾部增加指定元素的节点
        linkLast(e);//执行往尾部增加节点的方法
    }

    /**
     * Returns {@code true} if this list contains the specified element.
     * More formally, returns {@code true} if and only if this list contains
     * at least one element {@code e} such that
     * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>.
     *
     * @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;//返回校验结果,true代表有,false代表找不到
    }

    /**
     * Returns the number of elements in this list.
     *
     * @return the number of elements in this list
     */
    public int size() {//返回链表的长度
        return size;
    }

    /**
     * Appends the specified element to the end of this list.
     *
     * <p>This method is equivalent to {@link #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;//返回值
    }

    /**
     * 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
     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>
     * (if such an element exists).  Returns {@code true} if this list
     * contained the specified element (or equivalently, if this list
     * changed as a result of the call).
     *
     * @param o element to be removed from this list, if present
     * @return {@code true} if this list contained the specified element
     */
    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;//没有找到对应的节点则返回false
    }

    /**
     * Appends all of the elements in the specified collection to the end of
     * this list, in the order that they are returned by the specified
     * collection's iterator.  The behavior of this operation is undefined if
     * the specified collection is modified while the operation is in
     * progress.  (Note that this will occur if the specified collection is
     * this list, and it's nonempty.)
     *
     * @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) {//为链表增加一个集合对象
        return addAll(size, c);//调用具体的追加方法,传入当前链表的size以及待增加的集合对象
    }

    /**
     * Inserts all of the elements in the specified collection into this
     * list, starting at the specified position.  Shifts the element
     * currently at that position (if any) and any subsequent elements to
     * the right (increases their indices).  The new elements will appear
     * in the list in the order that they are returned by the
     * specified collection's iterator.
     *
     * @param index index at which to insert the first element
     *              from the specified collection
     * @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) {//为链表增加集合具体的追加方法
        checkPositionIndex(index);//校验参数合法性,不合法则抛出异常

        Object[] a = c.toArray();//将Collection对象转换为一个数组
        int numNew = a.length;//获取数组的长度
        if (numNew == 0)//如果是空数组则返回false
            return false;

        Node<E> pred, succ;//定义两个Node对象,pred指的是待插入对象位置的上一个对象,succ指的是待插入位置对象
        if (index == size) {//如果是通过构造方法初始化进来的数据,index则为size,代码388行,否则index则是调用方传入的
            //如果index=size,则代表插入的位置为链表的最末尾
            succ = null;//那succ肯定为null因为待插入对象位于链表末尾,因此将succ置为null
            pred = last;//因为待插入的对象位于链表末尾,所以该对象位置的上一个对象(pred)是待插入前的last节点
        } else {//如果插入的数据不为链表末尾
            succ = node(index);//根据传入的index值返回一个node对象succ,返回的对象代表index在链表中对应的位置的原node对象,即插入后变成下个node对象
            pred = succ.prev;//将succ的上一个节点指向pred
        }

        for (Object o : a) {//遍历数组对象
            @SuppressWarnings("unchecked") E e = (E) o;
            Node<E> newNode = new Node<>(pred, e, null);//根据数组里的元素构造每一个node对象
            if (pred == null)//如果pred为空则代表为当前列表头部
                first = newNode;//则将first(即链表的第一个元素)置为当前数组中的第一个node
            else//否则
                pred.next = newNode;//将上个对象的next属性替换为当前node节点,将pred与当前新增的node节点连接起来
            pred = newNode;//将当前的node节点置为pred以供后续新的node使用
        }

        if (succ == null) {//如果succ(即待插入的节点位置)为null则表示插入到链表末尾
            last = pred;//则将pred(遍历完了以后为最后一个添加的元素)置为last链表最后一个节点
        } else {//否则
            pred.next = succ;//将原本的节点位置succ作为最后插入的元素的next进行连接起来
            succ.prev = pred;//将原本的节点位置succ的prev与最后插入的元素的进行连接起来,即替换原本的prev
        }

        size += numNew;//对链表的总长度进行增加numNew为原本的数组的长度
        modCount++;//修改的次数,是个自增计数器,每调用一次修改链表的操作都会增加次数
        return true;//返回值
    }

    /**
     * Removes all of the elements from this list.
     * The list will be empty after this call returns.
     */
    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;//获取node对象的next节点先保存起来
            x.item = null;//将当前遍历到的对象的item置为null
            x.next = null;//将当前遍历到的对象的next置为null
            x.prev = null;//将当前遍历到的对象的prev置为null
            x = next;//将遍历对象指向下一个对象
        }//遍历结束即会将链表里的所有node都置为null
        first = last = null;//遍历会将链表的first与last属性置为null
        size = 0;//将链表的总长度置为0
        modCount++;//计数器自增
    }


    // Positional Access Operations

    /**
     * Returns the element at the specified position in this list.
     *
     * @param index index of the element to return
     * @return the element at the specified position in this list
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E get(int index) {//根据index获取元素具体值
        checkElementIndex(index);//校验index合法性
        return node(index).item;//首先根据index找到对应的node节点,再返回node的item属性
    }

    /**
     * Replaces the element at the specified position in this list with the
     * specified element.
     *
     * @param index index of the element to replace
     * @param element element to be stored at the specified position
     * @return the element previously at the specified position
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E set(int index, E element) {//根据index增加元素并返回修改前的元素
        checkElementIndex(index);//校验元素的合法性
        Node<E> x = node(index);//根据index获取当前位置的原node对象
        E oldVal = x.item;//将node的原值取出来保存
        x.item = element;//新的替换旧元素
        return oldVal;//返回修改前的元素
    }

    /**
     * Inserts the specified element at the specified position in this list.
     * Shifts the element currently at that position (if any) and any
     * subsequent elements to the right (adds one to their indices).
     *
     * @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) {//根据index新增元素
        checkPositionIndex(index);//校验index合法性

        if (index == size)//如果index == size则新增为元素末尾
            linkLast(element);//调用新增末尾的方法插入
        else//否则
            linkBefore(element, node(index));//调用非末尾方法进行新增
    }

    /**
     * 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.
     *
     * @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) {//根据index移除元素并返回移除的元素
        checkElementIndex(index);//校验index合法性
        return unlink(node(index));//首先根据index获取node节点位置再调用删除方法进行remove
    }

    /**
     * Tells if the argument is the index of an existing element.
     */
    private boolean isElementIndex(int index) {//校验取值时候的index是否合法逻辑是index必须>0并且要小于size
        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) {//新增元素的时候index的校验,判断index是否大于0并且小于size的总长度
        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) {//校验取值时候的index是否合法
        if (!isElementIndex(index))//不合法就抛出异常
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    private void checkPositionIndex(int index) {//校验新增元素时候的index是否合法
        if (!isPositionIndex(index))//如果index小于0或者大于size则抛出异常
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    /**
     * Returns the (non-null) Node at the specified element index.
     */
    Node<E> node(int index) {//根据index返回对应的node对象
        // assert isElementIndex(index);

        if (index < (size >> 1)) {//采用了优化算法,判断index与链表的头部还是尾部近,避免更多的遍历
            //如果与头部更近
            Node<E> x = first;//头部作为第一个循环的节点
            for (int i = 0; i < index; i++)//原理就是以i<index作为结束点则x.next即为要返回的node
                x = x.next;
            return x;//返回node节点
        } else {//如果与尾部更接近
            Node<E> x = last;//尾部作为第一个循环的节点
            for (int i = size - 1; i > index; i--)//原理就是以i>index作为结束点进行反向遍历则x.prev即为要返回的node
                x = x.prev;
            return x;//返回node节点
        }
    }

    // Search Operations

    /**
     * Returns the index of the first occurrence of the specified element
     * in this list, or -1 if this list does not contain the element.
     * More formally, returns the lowest 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 first occurrence of the specified element in
     *         this list, or -1 if this list does not contain the element
     */
    public int indexOf(Object o) {//根据元素判断节点的位置index,默认返回第一个匹配到的
        int index = 0;//初始化index为0
        if (o == null) {//若传入的值为null
            for (Node<E> x = first; x != null; x = x.next) {//遍历整个链表
                if (x.item == null)//若找到空值
                    return index;//返回index
                index++;//每循环一次index进行自增
            }
        } else {//若不是空值
            for (Node<E> x = first; x != null; x = x.next) {//遍历整个链表
                if (o.equals(x.item))//通过equals判断元素是否相同
                    return index;//返回index
                index++;//每循环一次index进行自增
            }
        }
        return -1;//找不到返回-1
    }

    /**
     * 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) {//根据元素返回最后一个匹配到的位置index
        int index = size;//初始化index为size
        if (o == null) {//若为空值
            for (Node<E> x = last; x != null; x = x.prev) {//以last作为起始元素进行反向遍历
                index--;//每循环一次index进行自减
                if (x.item == null)//若找到空值
                    return index;//返回index
            }
        } else {//不是空值
            for (Node<E> x = last; x != null; x = x.prev) {//以last作为起始元素进行反向遍历
                index--;//每循环一次index进行自减
                if (o.equals(x.item))//通过equals判断元素是否相同
                    return index;//返回index
            }
        }
        return -1;//找不到返回-1
    }

    // Queue operations.

    /**
     * Retrieves, but does not remove, the head (first element) of this list.
     *
     * @return the head of this list, or {@code null} if this list is empty
     * @since 1.5
     */
    public E peek() {//返回链表头部的元素值
        final Node<E> f = first;//获取链表头部
        return (f == null) ? null : f.item;//头部为空返回null,否则返回item
    }

    /**
     * Retrieves, but does not remove, the head (first element) of this list.
     *
     * @return the head of this list
     * @throws NoSuchElementException if this list is empty
     * @since 1.5
     */
    public E element() {//返回头部第一个元素,如果头部为空则抛出异常
        return getFirst();//返回头部第一个元素,如果头部为空则抛出异常
    }

    /**
     * Retrieves and removes the head (first element) of this list.
     *
     * @return the head of this list, or {@code null} if this list is empty
     * @since 1.5
     */
    public E poll() {//删除头部的节点并返回被删节点的元素值,头部为空则返回null
        final Node<E> f = first;//获取头部
        return (f == null) ? null : unlinkFirst(f);//否则调用删除头部的方法
    }

    /**
     * Retrieves and removes the head (first element) of this list.
     *
     * @return the head of this list
     * @throws NoSuchElementException if this list is empty
     * @since 1.5
     */
    public E remove() {//删除头部的节点并返回被删节点的元素值,头部为空则抛出异常
        return removeFirst();//调用删除头部的方法,头部为空则抛出异常
    }

    /**
     * Adds the specified element as the tail (last element) of this list.
     *
     * @param e the element to add
     * @return {@code true} (as specified by {@link Queue#offer})
     * @since 1.5
     */
    public boolean offer(E e) {//追加元素
        return add(e);//调用追加元素的方法
    }

    // Deque operations
    /**
     * Inserts the specified element at the front of this list.
     *
     * @param e the element to insert
     * @return {@code true} (as specified by {@link Deque#offerFirst})
     * @since 1.6
     */
    public boolean offerFirst(E e) {//往链表头部增加元素
        addFirst(e);//调用头部增加元素的方法
        return true;//返回值
    }

    /**
     * Inserts the specified element at the end of this list.
     *
     * @param e the element to insert
     * @return {@code true} (as specified by {@link Deque#offerLast})
     * @since 1.6
     */
    public boolean offerLast(E e) {//往链表尾部追加元素
        addLast(e);//调用往链表尾部追加元素的方法
        return true;//返回值
    }

    /**
     * Retrieves, but does not remove, the first element of this list,
     * or returns {@code null} if this list is empty.
     *
     * @return the first element of this list, or {@code null}
     *         if this list is empty
     * @since 1.6
     */
    public E peekFirst() {//获取链表头部的元素值,头部为空则返回null
        final Node<E> f = first;//获取链表头部
        return (f == null) ? null : f.item;//头部为空则返回null,否则返回f.item
    }

    /**
     * Retrieves, but does not remove, the last element of this list,
     * or returns {@code null} if this list is empty.
     *
     * @return the last element of this list, or {@code null}
     *         if this list is empty
     * @since 1.6
     */
    public E peekLast() {//返回链表尾部的元素值
        final Node<E> l = last;//获取链表尾部
        return (l == null) ? null : l.item;//尾部为空则返回null,否则返回l.item
    }

    /**
     * Retrieves and removes the first element of this list,
     * or returns {@code null} if this list is empty.
     *
     * @return the first element of this list, or {@code null} if
     *     this list is empty
     * @since 1.6
     */
    public E pollFirst() {//删除链表头部并返回被删除的元素
        final Node<E> f = first;//获取链表头部
        return (f == null) ? null : unlinkFirst(f);//头部为空则返回null,否则调用删除头部方法并返回
    }

    /**
     * Retrieves and removes the last element of this list,
     * or returns {@code null} if this list is empty.
     *
     * @return the last element of this list, or {@code null} if
     *     this list is empty
     * @since 1.6
     */
    public E pollLast() {//删除链表尾部并返回被删除的元素
        final Node<E> l = last;//获取链表尾部
        return (l == null) ? null : unlinkLast(l);//尾部为空则返回null,否则调用删除尾部方法并返回
    }

    /**
     * Pushes an element onto the stack represented by this list.  In other
     * words, inserts the element at the front of this list.
     *
     * <p>This method is equivalent to {@link #addFirst}.
     *
     * @param e the element to push
     * @since 1.6
     */
    public void push(E e) {//往头部增加节点
        addFirst(e);//调用头部增加节点的方法
    }

    /**
     * Pops an element from the stack represented by this list.  In other
     * words, removes and returns the first element of this list.
     *
     * <p>This method is equivalent to {@link #removeFirst()}.
     *
     * @return the element at the front of this list (which is the top
     *         of the stack represented by this list)
     * @throws NoSuchElementException if this list is empty
     * @since 1.6
     */
    public E pop() {//删除头部并返回被删除的元素
        return removeFirst();//调用删除头部的方法
    }

    /**
     * Removes the first occurrence of the specified element in this
     * list (when traversing the list from head to tail).  If the list
     * does not contain the element, it is unchanged.
     *
     * @param o element to be removed from this list, if present
     * @return {@code true} if the list contained the specified element
     * @since 1.6
     */
    public boolean removeFirstOccurrence(Object o) {//根据元素删除对应的节点,默认删除第一个匹配到的
        return remove(o);//调用删除方法
    }

    /**
     * Removes the last occurrence of the specified element in this
     * list (when traversing the list from head to tail).  If the list
     * does not contain the element, it is unchanged.
     *
     * @param o element to be removed from this list, if present
     * @return {@code true} if the list contained the specified element
     * @since 1.6
     */
    public boolean removeLastOccurrence(Object o) {//根据元素删除最后一个匹配到的节点
        if (o == null) {//如果值为null
            for (Node<E> x = last; x != null; x = x.prev) {//反向遍历
                if (x.item == null) {//找到为空的
                    unlink(x);//执行删除
                    return true;//返回
                }
            }
        } else {//不为空
            for (Node<E> x = last; x != null; x = x.prev) {//反向遍历
                if (o.equals(x.item)) {//找到相同的元素
                    unlink(x);//执行删除
                    return true;//返回
                }
            }
        }
        return false;//没找到删除的元素则返回false
    }



    private static class Node<E> {//内部类Node对象
        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;
        }
    }



    /**
     * Returns an array containing all of the elements in this list
     * in proper sequence (from first to last element).
     *
     * <p>The returned array will be "safe" in that no references to it are
     * maintained by this list.  (In other words, this method must allocate
     * a new array).  The caller is thus free to modify the returned array.
     *
     * <p>This method acts as bridge between array-based and collection-based
     * APIs.
     *
     * @return an array containing all of the elements in this list
     *         in proper sequence
     */
    public Object[] toArray() {//链表转为数组并返回数组
        Object[] result = new Object[size];//数组的长度为size
        int i = 0;
        for (Node<E> x = first; x != null; x = x.next)//遍历链表
            result[i++] = x.item;//根据数组index将node对象的元素值对其赋值
        return result;//返回新生成的数组
    }



}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值