I have a doubly linked list implementation as below :
public class DoublyLinkedList<T> {
DoublyLinkedListNode<T> head;
public DoublyLinkedListNode<T> getHead() {
return head;
}
public void setHead(DoublyLinkedListNode<T> head) {
this.head = head;
}
public void addNode(DoublyLinkedListNode<T> node) {
if(null == head) {
head = new DoublyLinkedListNode<>(node.getData());
}else{
traverseAndAdd(node);
}
}
private boolean traverseAndAdd(DoublyLinkedListNode<T> node) {
boolean isAdded = false;
DoublyLinkedListNode<T> tempHead = head;
do{
if(tempHead.getNext() == null) {
head.setNext(node);
node.setPrev(head);
isAdded = true;
break;
}
tempHead = tempHead.getNext();
}while(null != tempHead);
return isAdded;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
while(null != head) {
sb.append(head.getData());
head = head.getNext();
}
return sb.toString();
}
}
Below is my DoublyLinkedListNode class:
public class DoublyLinkedListNode<T> {
T data;
DoublyLinkedListNode<T> prev;
DoublyLinkedListNode<T> next;
public DoublyLinkedListNode(T data) {
this.data = data;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public DoublyLinkedListNode<T> getPrev() {
return prev;
}
public void setPrev(DoublyLinkedListNode<T> prev) {
this.prev = prev;
}
public DoublyLinkedListNode<T> getNext() {
return next;
}
public void setNext(DoublyLinkedListNode<T> next) {
this.next = next;
}
}
Now when I create an instance of DoublyLinkedList and try to add a node to it somehow my head instance variable is always null.
Even though i am initializing it in addNode method its always null when i am trying to add the next node.
Could someone please let me know if there is any problem with this implementation.
Below is how i am adding nodes to my list:
DoublyLinkedList<Integer> mylist = new DoublyLinkedList<>();
DoublyLinkedListNode<Integer> node1 = new DoublyLinkedListNode<>(10);
DoublyLinkedListNode<Integer> node2= new DoublyLinkedListNode<>(20);
DoublyLinkedListNode<Integer> node3 = new DoublyLinkedListNode<>(30);
DoublyLinkedListNode<Integer> node4 = new DoublyLinkedListNode<>(40);
DoublyLinkedListNode<Integer> node5 = new DoublyLinkedListNode<>(50);
DoublyLinkedListNode<Integer> node6 = new DoublyLinkedListNode<>(60);
mylist.addNode(node1);
mylist.addNode(node2);
mylist.addNode(node3);
mylist.addNode(node4);
mylist.addNode(node5);
mylist.addNode(node6);
System.out.println(mylist.toString());