Search code examples
javalinked-listnullpointerexception

LinkedList null pointer error. I keep on getting a null pointer exception when trying to print the elements in the LinkedList


I Keep on getting a null pointer exception when trying to print the elements in the list. The exception hits the line in the print() where I start the while loop. Is there a way to fix this? Thanks

class LinkedLists {

    private Node node;  

    public LinkedLists() {  
        
    }

    public void add(int d) {
        Node newNode = new Node(d);
        Node curr = node;
    
        if(curr == null) 
            curr = newNode;
    
    
        while(curr.next != null) {
            curr = curr.next;       
        }       
        curr.next = newNode;
    
        return;
    }

    public void print() {
    
        Node curr = node;
    
        while(curr.next != null) {
            System.out.println(curr.data);
            curr = curr.next;
        }
        System.out.println(curr.data);  
    }


    public static void main(String[] args) {
        LinkedLists list = new LinkedLists();
        list.add(3);
        list.add(12);
        list.add(99);
        list.add(6);
    
        list.print();       
    }

}

public class Node {

    Node next;
    int data;

    public Node(int d) {
        data = d;
        next = null;        
    }
}

Solution

  • Problem is you are always setting at the start.

    Node curr = node;
    

    you need to do that after the check.

    class LinkedLists {
    
        private Node headNode;  
    
        public LinkedLists() {  
            
        }
    
        public void add(int d) {
            Node newNode = new Node(d);
            //remove it from here 
            
            if(headNode == null) {
                headNode = newNode;
                return;
            }       
            //Added it here 
            curr = headNode;
            while(curr.next != null) {
                curr = curr.next;       
            }       
            curr.next = newNode;
        
            return;
        }
    
        public void print() {
        
            Node curr = headNode;
        
            while(curr.next != null) {
                System.out.println(curr.data);
                curr = curr.next;
            }
            System.out.println(curr.data);  
        }
    
    
        public static void main(String[] args) {
            LinkedLists list = new LinkedLists();
            list.add(3);
            list.add(12);
            list.add(99);
            list.add(6);
        
            list.print();       
        }
    
    }
    
    public class Node {
    
        Node next;
        int data;
    
        public Node(int d) {
            data = d;
            next = null;        
        }
    }