简体   繁体   中英

Adding elements into a LinkedList using ListIterator

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!

According to the documentation of ListIterator.add() the element you add is placed before the iterator's next element. That means even though you modify your list by adding an element, your current iterator won't consider it for its traversal. That's why your iteration stops after first loop.

In your second scenario. You have two nested loops, At the end of inner loop you create a new iterator for the list. This iterator is a fresh one which is starting from the beginning of the list again. So this piece of code works as you expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM