0

Guys I do have problem while inserting a new node at the end of a list. insert at begening works fine but in insert at end it shows null pointer exception.

Please look in method inserAtEnd and suggest me how to deal with it:

package linkedlist;

class Node{
    Node next;
    Object data;
    Node(Object x)
    {
        data=x;
    }
}
class LL
{
    Node first;

    LL(Node f)
    {
       first =f;
    }
    void insertAtBeg(Object x)
    {

        Node n= new Node(x);
        n.next=first;
        first=n;

    }
    void insertAtEnd(Object x)
    {
        Node n= new Node(x);
        Node k;
        k=first;
        while(k!=null)
        {
            k=k.next;
        }

      k.next=n;


    }
    void print()
    {

        Node p=first;
        while(p!=null)
        {

            System.out.print(p.data+"-->");
            p=p.next;
        }
    }

}
public class LinkedList {


    public static void main(String[] args) {
        LL l = new LL(null);
        l.insertAtBeg("Raj");
        l.insertAtBeg("Am ");
        l.insertAtBeg("I ");
        l.insertAtBeg("100 ");
        l.insertAtEnd("Hello");
        l.print();
        System.out.println("returned in main");

    }

}
3
  • 1
    Please provide the entire stack trace so we know where the error occurs. Commented Aug 2, 2015 at 16:37
  • 1
    Also, please add a language tag (It looks like Java, but I can't be sure). Additionally, please follow Java conventions (If this is even Java). Commented Aug 2, 2015 at 16:49
  • Next time i will take care of that :) Commented Aug 9, 2015 at 14:21

1 Answer 1

1

The problem is your loop is going till k is null, you want to go till k.next is equal to null. You could also solve it by having a variable for the last node(This is what is almost always done). The code I've provided fixes the problem without adding any new variables however:

void insertAtEnd(Object x) {
    Node n= new Node(x);
    Node k;
    k=first;

    while(k.next != null) {
        k=k.next;
    }

    k.next=n;
}
Sign up to request clarification or add additional context in comments.

3 Comments

My answer solves your problem, so would you mind accepting it or telling me what else I can add?
thank you Sir, your answer solved my problem. It works now :)
Glad I could help. I would appreciate it if you would accept my answer however.

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.