Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java iterator get next without incrementing

Tags:

java

I am writing the following loop in Java, for each loop I want to access the current and the next element of linked 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 might be wasting as everytime I call get(i), it start from the beginning so the run time order of the code is O(n^2). How do I achieve the same using Iterator (this time it will be O(n))? This is my first attempt:

while(it.hasNext()) {
    T current = it;
    T next = it.next();
}
like image 259
Dzung Nguyen Avatar asked Jun 26 '15 18:06

Dzung Nguyen


3 Answers

Maintain a variable previous that is equal to the previous loop's 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;
}

This will be O(n) because you are using the Iterator over your entire linked list.

like image 146
rgettman Avatar answered Sep 23 '22 07:09

rgettman


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;
}
like image 43
FredK Avatar answered Sep 25 '22 07:09

FredK


In each iteration, you should keep around a variable that will be the "current" and one that will be the "next". And you start processing your information starting from the second iteration, when you already have a current saved from the previous round.

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".
}

It's best to make sure that the list itself doesn't have null values. If it does, and it's a valid value, then you should have a boolean flag instead of just checking whether current != null.

like image 38
RealSkeptic Avatar answered Sep 21 '22 07:09

RealSkeptic