The Java iterator gets the next one without incrementing

I write the following loop in Java for each loop that I want to access the current and next elements of the link list 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);
    }

This can be wasteful because every time I call get (I), it starts from scratch, so the run-time order of the code is O (n ^ 2) How to use iterator to achieve the same function (this time o (n))? This is my first attempt:

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

Solution

Keep the variable previous previously equal to the current value of the previous cycle

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;
}

This will be o (n) because you use iterators throughout the list

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>