简体   繁体   中英

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. 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 . 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?

You're creating two nodes called first and last as part of the constructor of the Deque class.

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 .

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