I have been trying to create a deque in Java, but I get a nullpointer exception when I add a new node. Here is the helper class I use for the doubly-linked list:
private class Node {
private Item item;
private Node next;
private Node prev;
}
Then I add nodes to the beginning of the list as follows:
public void addFirst(Item item) {
Node oldfirst = first;
first = new Node();
first.prev = null;
first.item = item;
first.next = oldfirst;
oldfirst.prev = first;
N++;
}
I get a NullPointer
exception for the oldfirst.prev = first;
line. Also, when I compile the code I get the following warning:
Warning: The field Deque2<Item>.Node.prev is never read locally
What might I be doing wrong?
The exception means that oldfirst
is null. And you initialise it as Node oldfirst = first
, so it means that first
is null.