3

Having trouble adding nodes to the end of a linked The code is pretty self explanatory, the addToEnd method adds a single node to the end of a linkedlist.

public class ll5 {
    // Private inner class Node

    private class Node{
        int data;
        Node link;

        public Node(int x, Node p){
            data = x;
            link = p;
        }
    }
    // End of Node class

    public Node head;

    public ll5(){
        head = null;
    }

    public void addToEnd(int data) {
        Node p = head;
        while (p.link != null)
            p=p.link;
        p.link=new Node(data, null);
    }


    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        ll5 list = new ll5();

        list.printList();
        System.out.println("How many values do you want to add to the list");
        int toAdd = input.nextInt();

        for(int i = 0; i < toAdd; i++) {
            System.out.println("Enter value " + (i + 1));
            list.addToEnd(input.nextInt());
        }

        System.out.println("The list is:");
        list.printList();

        input.close();
    }

}

Why is it giving me an NullPointerException error?? The error is somewhere in the while loop in the addToEnd method.

1
  • I guess that Node p = head makes p = null since head is null when you call addToEnd the first time. Commented Apr 19, 2016 at 20:20

2 Answers 2

2

You haven't handled the initial condition when list has nothing and head is null. Because of that you're getting NPE.

Following method should work.

public void addToEnd(int data) {
    Node p = head;
    if( p == null) {
        head = new Node(data, null);
    } else {
        while (p.link != null)
            p=p.link;
        p.link=new Node(data, null);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

That's because the head is null at the beginning

public ll5(){
    head = null; // <-- head is null
}

public void addToEnd(int data) {
    Node p = head;  //<-- you assigned head, which is null, to p
    while (p.link != null) //<-- p is null, p.link causes NullException
        p=p.link;
    p.link=new Node(data, null);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.