I can add a new node if the head is empty, but I can't attach a new node. Instead I get a null pointer error. Can anyone see what I'm doing wrong. I think I've been staring at this for too long.
EDIT: Forgot to say I'm adding the Nodes in order. (I'm using a person class with an int in this particular situation, but it is supposed to take any class really).
public boolean add(E element){
Node<E> current = new Node(element);
if(this.head == null){
head = current;
size++;
return true;
}
else if(this.head.getNext() == null){
if( tail.getData().compareTo(head.getData()) == 0){
System.out.println("Value already in use. Not added to List.");
return false;
}
else{
tail = new Node(element, head, null);
size++;
return true;
}
}
else if(this.head != null && this.tail !=null){
current = head;
while(current != null){
if(element.compareTo(current.getData()) == 0){
System.out.println("Value already in use. Not added to List.");
return false;
}
else{
current = current.getNext();
}
}
current = new Node(element, current.getPrevious(), current.getNext());
return true;
}
return false;
}
My Node implementation
public class Node<E>{
private E data;
private Node prev;
private Node next;
public Node(E element){
this(element, null, null);
}
public Node(E element, Node n){
this(element, n, null);
}
public Node(E element, Node n1, Node n2){
this.data = element;
this.prev = n1;
this.next = n2;
}
public void setPrevious(Node n){
this.prev = n;
n.next = this;
}
public void setNext(Node n){
this.next = n;
n.prev = this;
}
public Node getNext(){
return this.next;
}
public Node getPrevious(){
return this.prev;
}
public void setData(E element){
this.data = element;
}
public E getData(){
return this.data;
}
}