简体   繁体   English

使用ListIterator将元素添加到LinkedList中

[英]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. 在使用Java中的ListIterator将元素添加到LinkedList时,我需要一些帮助来理解基本行为。 Please look at the code below: 请看下面的代码:

Here, graphQueue initially has only one Node. 在这里, graphQueue最初只有一个节点。 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; 我的逻辑是删除主Node并将其子级添加到graphQueuegraphQueue进行迭代,然后将其子级添加到队列中,依此类推...假设我将vertex 0添加到队列中; and it has three children 2, 3, & 5. I am removing 0 from Queue and I am adding 2, 3 & 5 into the queue. 它有三个孩子2、3和5。我从队列中删除0,然后将2、3和5添加到队列中。

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. 现在的问题是循环在第一个循环之后退出,但是如果我在这个while循环周围再做一次while循环并再次创建Iterator对象,它会起作用。 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. 根据ListIterator.add()文档 ,您添加的元素位于迭代器的下一个元素之前。 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. 因此,这段代码可以按预期工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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