Here's my Node object:
public class Node<Any> {
protected Any data;
protected Node<Any> link;
public Node() {
this.data=null;
this.link=null;
}
public Node(Any data, Node<Any> link) {
this.data=data;
this.link=link;
}
public void setData(Any data) {
this.data=data;
}
public void setLink(Node<Any> link) {
this.link=link;
}
public Any getData() {
return this.data;
}
public Node<Any> getLink() {
return this.link;
}
public String toString() {
return "Data: "+this.data+" | Link: "+this.link;
}
}
And here's my SinglyLinkedList object:
public class SinglyLinkedList<Any> {
private Node<Any> head;
private Node<Any> tail;
private int size;
public SinglyLinkedList() {
this.head=null;
this.tail=null;
this.size=0;
}
//overloaded constructor for array to be added here
public void insertAsHead(Any thing) {
Node<Any> tmp=new Node<Any>(); //Create new node
tmp.data=thing; //new_node->node.data=new_value
tmp.link=this.head; //new_node->node.link=head
this.head=tmp; //head=new_node
size++;
}
public void insertAsTail(Any thing) {
if(head==null)
insertAsHead(thing);
else {
Node<Any> tmp = new Node<Any>(); //Create new node
tmp.data=thing; //new_node->node.data=new_value
tmp.link=null; //new_node->node.link=null
this.tail.link=tmp; //tail->node.link=new_node
this.tail=tmp; //tail=new_node;
}
size++;
}
public void insertBefore(int i, Any thing) {
}
public void insertAfter(int i, Any thing) {
}
public void insertAt(int i, Any thing) {
}
public void deleteHead() {
size--;
}
public void deleteTail() {
size--;
}
public void deleteAt(int i) {
size--;
}
public Any retrieve(int i) {
return null;
}
public void set(int i, Any thing) {
}
public boolean isEmpty() {
if(this.size==0)
return true;
else
return false;
}
public int size() {
return this.size;
}
public String toString() {
String s="["+this.head.data;
Node<Any> next = this.head.link;
while(next!=null) {
s+=", "+next.data;
next=next.link;
}
return s+"]";
}
}
Whenever I use the method 'insertAsTail(x)' when linked list contains values, the program execution halts and says that there is a NullPointerException at the line this.tail.link=tmp; //tail->node.link=new_node
. I have tried going for the this.tail.setLink(tmp)
route but same exception occurs.