LinkedList添加元素和移除元素源代码之我见

LinkedList:本质是一个双向链表。

节点:

添加元素(找了好几个图,感觉会误导就不贴出来,直接贴源码吧)

  //Node的数据结构:
    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;
        }
    } 



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


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



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

    //
       public void add(E e) {
            checkForComodification();
            lastReturned = null;
            if (next == null)
                linkLast(e);
            else
                linkBefore(e, next);
            nextIndex++;
            expectedModCount++;
        }


    /**
     * 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) {
        checkPositionIndex(index);

        if (index == size)
            linkLast(element);
        else
            linkBefore(element, 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
     * <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;
    }


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

通过索引移除元素:移除元素会有一个查找元素的过程,当前索引位置小于链表长度1/2时候,从首节点开始往后面扫描。

当前索引位置大于链表长度的1/2时候,从尾节点往前面扫描。

    /**
     * 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) {
        checkElementIndex(index);
        return unlink(node(index));
    }

    /**优化双向链表查询索引的过程:
       当前索引和链表长度的1/2做比较,小于1/2,从头节点开始往后遍历。
       大于1/2,从尾节点开始往前遍历。
    
     * 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;
        }
    }

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值