0

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();
    }
}
Ruben
  • 3
  • 2
  • Well, I read through that but i can't figure out how to initialize the Node, I mean, i do first = null, but keeps throwing the same NullPointerExeption when i do first.data.equals(null) – Ruben Oct 08 '16 at 15:59
  • probably change `addFirst(T x)` to a `addFirst(Node root)` method – Mad Matts Oct 08 '16 at 16:03
  • don't use equals to check for null, you probably want `if (first.data == null){` and some init of `first` (like in provided answer) –  Oct 08 '16 at 16:06
  • You should check `first == null`, then. Obviously `first.data` => `null.data` is the problem – OneCricketeer Oct 08 '16 at 16:06

1 Answers1

2

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) {
Andriy Kryvtsun
  • 3,220
  • 3
  • 27
  • 41