繁体   English   中英

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

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

我写了一种方法,可以在双向链表的前面添加一个项目。 每次调用该函数时,它都应添加通过它传递的项。 该功能按预期工作,除了当我遍历双向链接列表并打印每个项目时,它总是在末尾打印两次null 我的代码如下。

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);
            }
    }

该代码显示: 9, 5, 7, 1, null, null 我无法弄清楚正在打印两个额外的空值。 谁能告诉我如何解决我的代码,使代码最后不两次输出null

您正在创建两个名为firstlast节点,作为Deque类的构造函数的一部分。

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

因此,您的物品会被添加到它们的前面。 当您打印出来时,它会打印您添加的内容,然后打印第一和最后一个,并且由于它们没有设置项目,因此它会打印null

暂无
暂无

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

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