I am working on my Computer Science studies and I am having some difficulty with adding a Node to the end of a doubly linked-list data structure. I understand that the new node points to the tail and the tail points to it, thus I have this:
public boolean add(E element)
{
// TODO: Implement this method
LLNode<E> newNode = new LLNode<E> (element);
if (element == null) {
throw new NullPointerException("Element can not store a null reference!");
} else {
newNode.next = tail;
newNode.prev = tail.prev;
tail.prev = newNode;
head.next = newNode;
}
size++;
return true;
}
The issue I'm having is trying to connect the head node (via head.next to the correct node).
In my default constructor, I have the head.next node pointing to tail.prev. However in the add method, I could not figure out where head.next would point since each time you add a new node, head has to point to the first node in the LinkedList Data Structure. Here is the default constructor:
public MyLinkedList() {
// TODO: Implement this method
size = 0;
/*create two empty nodes at the head and the tail of the linked list*/
head = new LLNode<E> (null);
tail = new LLNode<E> (null);
head.next = tail;
tail.prev = head;
head.prev = null; //Head is a sentinel node with no node prior to it
tail.next = null; //tail is a sentinel node with no node after it
}
Please point me (no pun intended) to the right direction. Thanks!
Element can not store a null reference!
... says who? The marker for the end of a list is not that the element being stored is null, it is that the next pointer is null. – Tim Biegeleisen