我正在用 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)。如何使用迭代器实现相同的目标(这次将是 O(n))?这是我的第一次尝试:
while(it.hasNext()) {
T current = it;
T next = it.next();
}
维护一个变量previous
等于前一个循环的current
value.
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
覆盖您的整个链接列表。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)