I'm not able to find where the error occurs and the solution to it.
The error says head is null but I have already checked for the condition where head==null
Source Code
public class LinkedList {
Node head;
void add(int data) {
Node toAdd = new Node(data);
Node temp = head;
if (head == null) {
head.next = toAdd;
}
else {
while (temp.next != null) {
temp = temp.next;
}
temp.next = toAdd;
}
}
void printList() {
Node temp = head;
while (temp != null) {
System.out.println(temp.data);
temp = temp.next;
}
}
public static class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
next = null;
}
}
public static void main(String[] args) {
LinkedList ll = new LinkedList();
ll.add(2);
ll.add(6);
ll.printList();
}
}
Error
Exception in thread "main" java.lang.NullPointerException: Cannot assign field "next" because "this.head" is null
at LinkedList.add(LinkedList.java:10)
at LinkedList.main(LinkedList.java:41)