I need some help in Understanding the underlying behavior while adding elements into a LinkedList using ListIterator in java. Please look at the code below:
Here, graphQueue initially has only one Node. And that Node has three children which are also Nodes.
My logic is to remove the main Node and add its children into the graphQueue for iterating over them and add their children into the queue and so on...
Let's say I have vertex 0 which is added in queue; and it has three children 2, 3, & 5. I am removing 0 from Queue and I am adding 2, 3 & 5 into the queue.
ListIterator<Node> it = graphQueue.listIterator();
while (it.hasNext())
{
Node node = it.next();
it.remove();
if (node.hasChildren())
{
for (Node child : node.getChildren())
{
it.add(child);
}
}
}
Now the problem is the loop exits after first loop, but it works if I put one more do while loop around this while loop and creating Iterator object again. Please look at the below code:
ListIterator<Node> it = graphQueue.listIterator();
do
{
while (it.hasNext())
{
Node node = it.next();
it.remove();
if (node.hasChildren())
{
for (Node child : node.getChildren())
{
it.add(child);
}
}
}
it = graphQueue.listIterator();
} while(it.hasNext());
Am I missing something? Thanks!