Question

the following splitter method is designed to return a IntLinkedBag array of two separate linked lists. It accomplishes this by calling listSplitLessGreater method and passes the head reference of a linked list of integers and a splitter integer value which returns an IntNode array that contains the head reference of two new linked lists of integers that have been sorted. The splitter method works as written. It was the only way I could get it to work. But I know there has to be an easier/better way to code it. everything between the //******** I want to replace with this

newLists[0].head = answer[0]; 
newLists[1].head = answer[1];

But when I do I receive null pointer exemption errors when running the program. My question is why? and how is the correct way to write this code?

 public IntLinkedBag[] splitter(int target)
{
    IntLinkedBag[] newLists = new IntLinkedBag[2]; 
    IntNode[] answer = new IntNode[2];
    answer = IntNode.listSplitLessGreater(head, target);

    //**********************************
    IntLinkedBag b = new IntLinkedBag();
    IntLinkedBag c = new IntLinkedBag();
    b.add(5);
    b.head = answer[0];
    newLists[0] = b;
    c.add(5);
    c.head = answer[1];
    newLists[1] = c;
    //**********************************

    return newLists;
}

I updated my code like to below. I get no errors, but it now isn't returning anything. Even though the test code prints the linked list.... and idea's?

  public IntLinkedBag[] splitter(int target)
{
    IntLinkedBag[] newLists = {new IntLinkedBag(), new IntLinkedBag()}; 

    IntNode[] answer = new IntNode[2];
    answer = IntNode.listSplitLessGreater(head, target);


        newLists[0].head = answer[0]; 
    newLists[1].head = answer[1];



    System.out.println(IntNode.showList(newLists[0].head)); //test code
    System.out.println(IntNode.showList(newLists[1].head)); //test code

    return newLists;
}

adding this code gets it to work but why is this required?

newLists[0].add(5); //adding a number to linked list to create a temporary head.
newLists[1].add(5); //don't know why I have to have this but its only way code works correctly
Was it helpful?

Solution

There's nothing actually initialized inside of newlists[0] or newlists[1]; the array creates default values of null on creation.

Try something like this:

IntLinkedBag[] newLists = new IntLinkedBag[2];
for(int i = 0; i < newLists.length; i++) {
    newLists[i] = new IntLinkedBag();
}

More compact, you could do this:

IntLinkedBag[] newLists = {new IntLinkedBag(), new IntLinkedBag()};

That does the same thing without a loop.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top