【问题标题】:Java iterator get next without incrementingJava迭代器在不递增的情况下获得下一个
【发布时间】:2015-06-26 18:54:46
【问题描述】:

我正在用 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();
}

【问题讨论】:

  • 您使用的是哪个 List 实现?我假设 LinkedList 因为 ArrayList 有 O(1) 用于获取...

标签: java


【解决方案1】:

维护一个变量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

【讨论】:

  • 太棒了!那么 it.next() 会自动将迭代器移动到下一个?
  • @clcto 在第一次迭代中,没有previous,所以我将它初始化为null。如果处理“null, first element”对没有意义,那么您可以通过添加if(it.hasNext()) previous = it.next(); 对其进行初始化,这样while 循环将只处理列表中的实际对。
  • @DzungNguyen 是的,每次调用next() 总是返回下一个项目,除非没有更多项目,在这种情况下它会抛出一个NoSuchElementException
【解决方案2】:

在每次迭代中,您应该保留一个变量,一个是“当前”,一个是“下一个”。并且您从 second 迭代开始处理您的信息,此时您已经从上一轮保存了 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

【讨论】:

    【解决方案3】:
    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;
    }
    

    【讨论】:

    • 这个答案出现在低质量审查队列中,大概是因为您没有解释代码。如果你确实解释了(在你的回答中),你更有可能获得更多的支持——提问者更有可能学到一些东西!
    猜你喜欢
    • 2023-03-14
    • 2020-12-13
    • 2021-05-04
    • 1970-01-01
    • 2019-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-07
    相关资源
    最近更新 更多