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

时间:2015-06-26 18:54:47

标签: 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);
    }

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

while(it.hasNext()) {
    T current = it;
    T next = it.next();
}

3 个答案:

答案 0 :(得分: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;
}

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

答案 1 :(得分:3)

在每次迭代中,你应该保留一个变量,它将是&#34; current&#34;并且将成为&#34; next&#34;。当您已经从上一轮保存current时,您就开始从第二次迭代开始处理您的信息。

T current = null;
T next = null;
Iterator<T> iter = r.iterator();

while ( iter.hasNext() ) {

    next = iter.next();
    if ( current != null ) { // Passed the first iteration

        // Now you can use current and next, they both have values.

    }
    current = next; // Save what was the "next" as the next "current".
}

最好确保列表本身没有空值。如果是,并且它是一个有效值,那么你应该有一个布尔标志,而不仅仅是检查是否current != null

答案 2 :(得分:0)

T current = r.get(0);
for ( int i=0; i < r.size()-1; i++ ) {
   T next = r.get(i+1);
     // do stuiff here
   current = next;
}