0

The problem arises in the merge function at 'while(m.next!=null)'. It throws a "NullPointerException".

public class Linked {

    node ptr1;
    node ptr2;

    void merge()
    {
        node m=ptr1;

        while(m.next!=null)
            m=m.next;
        m.next=ptr2;
    }

    void printmerged()
    {
        node m=ptr1;

        while(m.next!=null)
            System.out.print(m.data+", ");
        System.out.println(m);
    }
}
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95

1 Answers1

1

I added comments to your code to explain to you what's going on.

node ptr1; //ptr1 is null here
node ptr2;

void merge()
{
    node m=ptr1; //you are assigning null to m

    while(m.next!=null) //you are accessing the "next" property of a null object
        m=m.next;
    m.next=ptr2;
}

You have to instantiate your objects otherwise they are going to be null.

A.Sharma
  • 2,771
  • 1
  • 11
  • 24