共同学习Java源代码--数据结构--LinkedList类(五)

    public int size() {
        return size;

    }

这个方法返回list的长度。

    public boolean add(E e) {
        linkLast(e);
        return true;
    }

这个方法是将元素添加到链表末尾的方法,调用linkLast方法。最后返回true,这个有点奇怪,就算是添加失败也返回true?

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

这个方法是删除某个元素的方法。

先判断参数如果为空,就遍历链表,然后判断哪个元素为空,就调用unlink方法删除哪个元素,然后返回true。

如果元素不为空,同样遍历链表,判断哪个元素“”等于“”参数,然后就调用unlink方法删除哪个元素,然后返回true。

如果始终没有遍历到元素,说明链表中不存在该元素,就直接返回false。

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

这个方法就是清空所有元素的方法,就是遍历然后把所有节点和所有节点的关联都置为空,然后size为空,最后修改次数modCount自增。

    public E get(int index) {
        checkElementIndex(index);
        return node(index).item;
    }

这个方法调用了下面的方法获取元素内容并返回,之前检查参数传递进去的下标是否越界。

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

这个方法接收一个下标参数,返回参数对应的节点。

这个方法的实现比较有意思,用的是类似二分法查找。

首先判断参数是不是在size的前一半以内,如果是就从开头开始向后遍历,一直获取到index那里的节点然后返回。

如果参数不在size的前一半以内,就从最后开始向前遍历,一直获取到index那里的节点然后返回。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值