0

This code:

package Datastructures;

public class ChainNode {

    Object element;
    ChainNode next;

    public ChainNode() {
    }

    public ChainNode(Object element) {
        this.element = element;
    }

    public ChainNode(Object element, ChainNode next) {

        this.element = element;
        this.next = next;
    }

    public static void main(String args[]) {
        ChainNode firstNode = new ChainNode("a");
        ChainNode newNode = new ChainNode("b", firstNode.next);
        ChainNode newNode2 = new ChainNode("c", firstNode.next.next);
        System.out.println(firstNode.element);
        System.out.println(newNode.element);
    }

}

Stack trace:

Exception in thread "main" java.lang.NullPointerException
    at Datastructures.ChainNode.main(ChainNode.java:24)
Ashot Karakhanyan
  • 2,804
  • 3
  • 23
  • 28
Ochirbold Manal
  • 161
  • 1
  • 9

1 Answers1

0

That is because you construct subsequent ChainNode objects and give them a null reference to the previous object's next field, while you should be giving a reference to the previous object itself. Try this:

public static void main(String args[]) {

    ChainNode firstNode = new ChainNode("a");
    ChainNode newNode = new ChainNode("b", firstNode);
    ChainNode newNode2 = new ChainNode("c", newNode); 

    System.out.println(firstNode.element);
    System.out.println(newNode.element);
}
Bartek Maraszek
  • 1,404
  • 2
  • 14
  • 31