I am trying to implement data structure Linked List (Singly) however by adding elements returns NULLPOINTEREXCEPTION.
import java.util.NoSuchElementException;
public class Linkedlist<ANYTYPE>{
private Node head;
Linkedlist(){
head = null;
}
public void add(ANYTYPE data){
head.next = new Node<>(data, head);
}
public void traverse(){
if(head == null) throw new NoSuchElementException("List may be empty");
Node temp = head;
while(temp != null){
System.out.println(temp.data+" ");
temp = temp.next;
}
}
public static void main(String[] args) {
Linkedlist<String> l=new Linkedlist<String>();
l.add("one");
l.add("two");
l.traverse();
}
private class Node<ANYTYPE>{
private ANYTYPE data;
private Node next;
Node(ANYTYPE data, Node next){
this.data = data;
this.next = next;
}
}
}