简体   繁体   English

为什么我的双向链表迭代器打印为空?

[英]Why does my doubly linked list iterator print null?

I wrote a method that adds an item to the front of a doubly linked list. 我写了一种方法,可以在双向链表的前面添加一个项目。 Every time I call the function, it should add the item passed through it. 每次调用该函数时,它都应添加通过它传递的项。 The function works as expected, except for when I iterate through the doubly linked list and print each item, it always prints null twice at the end. 该功能按预期工作,除了当我遍历双向链接列表并打印每个项目时,它总是在末尾打印两次null My code is below. 我的代码如下。

public Deque() {
        first = new Node();
        last = new Node();
        first.next = last;
        last.prev = first;  
    }
public void addFirst(E item) {

        if (item.equals(null)) {
            throw new NullPointerException();
        } else {

        if (first.equals(null) && last.equals(null)) {
            first = new Node();
            first.next.item = item;
            first.next.next = null;
            last = first;
        } else {
            Node node = new Node();
            node.item = item;
            node.next = first;
            first = node;
        }
    }
        N++;

    }

public static void main(String[] args) {

        Deque<Integer> lst = new Deque<Integer>(); // empty list

          lst.addFirst(1);
          lst.addFirst(5);
          lst.addFirst(7);
          lst.addFirst(9);  

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

That code prints: 9, 5, 7, 1, null, null . 该代码显示: 9, 5, 7, 1, null, null I cannot figure out the two extra null values are being printed. 我无法弄清楚正在打印两个额外的空值。 Can anybody tell me how I can fix my code so that it does not print null two times at the end? 谁能告诉我如何解决我的代码,使代码最后不两次输出null

You're creating two nodes called first and last as part of the constructor of the Deque class. 您正在创建两个名为firstlast节点,作为Deque类的构造函数的一部分。

public Deque() {
    first = new Node();
    last = new Node();
    first.next = last;
    last.prev = first;  
}

So, your items get added in front of them. 因此,您的物品会被添加到它们的前面。 When you print them out, it prints the ones you added and then first and last, and since they don't have an item set, it prints null . 当您打印出来时,它会打印您添加的内容,然后打印第一和最后一个,并且由于它们没有设置项目,因此它会打印null

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

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