package e17;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.Random;
public class OrdenLink {
static Random ran=new Random();
public static void main(String[] args) {
// TODO Auto-generated method stub
LinkedList<Integer> list=new LinkedList<Integer>();
for(int i=0; i<25; i++) {
Integer n=ran.nextInt(100);
if(list.isEmpty()) list.add(n);
else {
ListIterator<Integer>it=list.listIterator();
while(it.hasNext())
if(it.next()>n) it.add(n);
}
}
}
}
I'm trying to insert 25 random numbers in an orderly fashion into a LinkedList with a listiterator. I think the Listiterator's add insert just before the next(); or after previous();. I've given it several times but it throws me either NoSuchElementException or OutOfBounds. Can someone shed some light on this dark road?
You have two problems: 1- If n is the largest in the list, it is not inserted. 2- Every time you read the next, it changes to the next position. That is, when you compare next()>n, the "next pointer" has already moved forward, altering what the add() method does.
For point 1, it is enough to put a flag that indicates if the element was inserted or not, and then outside the while check the flag and do the add if it was not done before.
For point 2, a half hacky solution is to call previous after reading next() to move the pointer back one position. And break the loop because in an ordered list, once an element is less than one element in the list, it's also less than all the elements that follow.
Hint: Avoid single line if and while, they will give you headaches.