【问题标题】:Is linkedList.listIterator(linkedList.size()) optimized?linkedList.listIterator(linkedList.size()) 优化了吗?
【发布时间】:2015-05-09 09:56:24
【问题描述】:

我正在尝试为LinkedList 创建一个反向ListIterator,并将其作为linkedList.listIterator(linkedList.size()) 的包装器实现,以交换nextprevious 操作,但随后意识到如果 LinkedList#listIterator(int) 被实现为仅向前遍历到指定的位置,那么使用它从末尾开始将是非常未优化的,当列表支持直接到末尾时,必须遍历列表两次而不是一次。 linkedList.listIterator(linkedList.size()) 是否优化为不遍历整个列表?

【问题讨论】:

  • 这是非常具体的实现

标签: java linked-list reverse listiterator


【解决方案1】:

ListIterator 使用索引来标识从哪个元素开始。 In the Oracle docs for LinkedList,上面写着:

所有操作都按预期执行双重链接 列表。索引到列表中的操作将遍历列表 开始或结束,以更接近指定索引为准。

因此,当您执行linkedList.listIterator(linkedList.size()) 时,它将正好向后遍历列表 0 步以获取正确的索引。因此,您可以说它已尽可能优化。继续包装该迭代器。

【讨论】:

    【解决方案2】:

    优化好了,就在这里

    private class ListItr implements ListIterator<E> {
    

    ...

    ListItr(int index) {
        // assert isPositionIndex(index);
        next = (index == size) ? null : node(index);
        nextIndex = index;
    }
    

    ...

    Node<E> node(int index) {
        // assert isElementIndex(index);
    
        if (index < (size >> 1)) {  <-- if index less than half size go forward
            Node<E> x = first;
            for (int i = 0; i < index; i++)
                x = x.next;
            return x;
        } else {                     <-- otherwise backwards
            Node<E> x = last;
            for (int i = size - 1; i > index; i--)
                x = x.prev;
            return x;
        }
    }
    

    【讨论】:

    • 实现的来源?
    • 它在我的 JDK - src.zip
    • @Quirliom Grepcode 也是一个很好的资源,如果你不能轻易拆开 src.zip:ListItr in LinkedList
    猜你喜欢
    • 2019-08-06
    • 2017-12-12
    • 2021-06-14
    • 2012-03-01
    • 2020-01-06
    • 2015-12-22
    • 2018-02-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多