0

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)
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • You explicitly dereference `head` while it is `null` in your `add` method. – Mark Rotteveel Jan 21 '21 at 11:00
  • When head is null, make a new node and assign it to head, not head.next – Jems Jan 21 '21 at 11:01
  • `if(head == null) { head.next = toAdd; }` what do you expect to happen here? Of course `head.next` will cause a NPE because `head` is null. Did you mean `head = toAdd;` instead? - Hint: stepping through your code with a debugger should reveal those things quite easily. – Thomas Jan 21 '21 at 11:02

0 Answers0