Reputation: 1726
I am trying to write a function addFirst()
that takes an item and inserts it at the front of a doubly linked list. The doubly linked list has two dummy nodes, one on each end. The addFirst()
method that I wrote so far only returns to two dummy nodes when I iterate through the list and print it. I cannot figure out what is wrong with my code.
public void addFirst(E item) {
if (item.equals(null)) { throw new NullPointerException(); }
Node node = new Node(item, null);
Node ptr = first;
ptr.next.prev = node;
node.prev = ptr;
node.next = ptr.next;
}
public static void main(String[] args) {
Deque<Integer> lst = new Deque<Integer>(); // empty list
lst.addFirst(1);
lst.addFirst(2);
lst.addFirst(3);
Iterator<Integer> it = lst.iterator(); // tests iterator method
while (it.hasNext()) {
Integer val = it.next();
System.out.println(val);
}
}
When I run main, all I get is:
null null
However, I expect:
null 3 2 1 null
Can anybody show me how I can fix my code so that I can add an item at the start of my doubly linked list in between the two dummy first and last nodes?
Upvotes: 0
Views: 684
Reputation: 1726
I found what I did wrong. I just needed to complete the chain by adding the line
ptr.next = node;
So my full code for this method looked like this:
public void addFirst(E item) {
if (item.equals(null)) { throw new NullPointerException(); }
Node node = new Node(item, null);
Node ptr = first;
ptr.next.prev = node;
node.prev = ptr;
node.next = ptr.next;
ptr.next = node;
}
Upvotes: 1