简体   繁体   English

在遍历双向链表时如何跳过空虚拟节点

[英]How to skip null dummy nodes when traversing doubly linked lists

I have a doubly linked list which looks like: 我有一个双向链接列表,如下所示:

null 1 2 3 null

When I traverse the list using an iterator with the code below, the output prints exactly what is written above. 当我使用带有以下代码的迭代器遍历列表时,输出将完全打印上面编写的内容。

            Iterator<Integer> it = lst.iterator(); // tests iterator method
            while (it.hasNext()) {
              Integer val = it.next();

              System.out.println(val);
            }

However, I want to skip the null nodes as I traverse the list so that it only prints: 但是,我想在遍历列表时跳过空节点,以便仅打印:

1 2 3

I cannot get my code to do that. 我无法获得执行此操作的代码。 Here is what I have come up with so far. 到目前为止,这是我想出的。

            Iterator<Integer> it = lst.iterator(); // tests iterator method
            while (it.hasNext()) {
              Integer val = it.next();
              if (val == null)
                 it.next()

              System.out.println(val);
            }

The problem with that is that I get a NoSuchElementException error, but I cannot figure out how to fix it. 问题是我收到了NoSuchElementException错误,但是我不知道如何解决它。 My guess is I get that error because when I get to the second null dummy node, I try to skip it, but there are no other nodes to jump to. 我的猜测是我得到了这个错误,因为当我到达第二个空虚拟节点时,我尝试跳过它,但是没有其他节点可以跳转。

My question is, how can I change my code so that it prints each element in the doubly linked list while skipping both of the null dummy nodes? 我的问题是,我该如何更改代码,以便在跳过两个空虚拟节点的同时打印双向链接列表中的每个元素?

All you have to do is to use the test in combination with the println: 您要做的就是将测试与println结合使用:

while (it.hasNext()) {
   Integer val = it.next();
   if (val != null){
       System.out.println(val);
   }
}

If you do an extra next in the loop, you skip one hasNext, and that's why you run into the exception. 如果在循环中执行额外的下一步,则跳过一个hasNext,这就是您遇到异常的原因。

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

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