Java迭代器在没有递增的情况下获得下一个

Dzu*_*yen 4 java

我在Java中编写以下循环,对于我想要访问链接列表r的当前和下一个元素的每个循环:

    List<T> r = new LinkedList();

    for (int i=0; i < r.size() - 1; i++) {
        T current = r.get(i);
        T next = r.get(i+1);
    }
Run Code Online (Sandbox Code Playgroud)

这可能是浪费,因为每当我调用get(i)时,它从头开始,因此代码的运行时顺序为O(n ^ 2).如何使用Iterator实现相同的功能(这次是O(n))?这是我的第一次尝试:

while(it.hasNext()) {
    T current = it;
    T next = it.next();
}
Run Code Online (Sandbox Code Playgroud)

rge*_*man 8

保持一个previous等于前一个循环current值的变量.

T previous = null;
// If it makes sense to skip the first "null, first element" pair...
if (it.hasNext())
{
    previous = it.next();
}    

while (it.hasNext())
{
    T current = it.next();
    // Process previous and current here.

    // End of loop, after processing.  Maintain previous reference.
    previous = current;
}
Run Code Online (Sandbox Code Playgroud)

这将是O(n),因为您使用的是Iterator整个链表.