Search code examples
javadata-structurescircular-list

java.lang.NullPointerException when trying to add elements to a circular linked list


I'm trying to add an element to the circular linked list but it throws NullPointerException whenever I try to access the node. Here's my code: EDIT: I already read the post explaining NullPointerExceptions but nothing worked.

public class CircularLinkedList<T> {
static private class Node<T> {
    public T data;
    public Node<T> next;

    Node(T data, Node<T> next) {
        this.data = data;
        this.next = next;
    }
}

private Node<T> first;

public void addFirst(T x){
    if (first.data.equals(null)){
        first.data = x;
        first.next = first;
    }else{
        Node<T> second = first;
        first.data = x;
        first.next = second;
    }
}

EDIT: I already initialized the Node with private Node<T> first = new Node(null, null);, keeps throwing the error. Also compared with first.data == null, now it terminates the process.

EDIT:Here's the full code:

public class CircularLinkedList<T> {
    static private class Node<T> {
        public T data;
        public Node<T> next;

        Node(T data, Node<T> next) {
            this.data = data;
            this.next = next;
        }
    }

    private Node<T> first = new Node(null, null);

    public void addFirst(T x){
        if (first.data == null){
            first.data = x;
            first.next = first;
        }else{
            Node<T> second = first;
            first = new Node(x, second);
        }
    }

    public void print() {
        while (first.data == null) {
            System.out.println(first.data);
            first = first.next;
        }
    }

    public static void main(String[] args) {
        CircularLinkedList<String> lst = new CircularLinkedList<String>();
        lst.addFirst("Z");
        lst.addFirst("A");
        lst.addFirst("B");
        lst.print();
    }
}

Solution

  • You get NPE in first.data.equals(null) statement as initially first variable itself is null. You have to initialize it at start like this

    private Node<T> first = new Node(null, null);
    

    Also you have to compare with null differently

    if (first.data == null) {