smooth_smoothie
smooth_smoothie

Reputation: 1343

Having issue with 'Null pointer access' in Java

if(key == '1'){//insert at ->right.right
    BinaryNode tempPointer = root;

    while(tempPointer != null){
        tempPointer = tempPointer.right;
    }
    BinaryNode newNode = new BinaryNode(x);
    newNode.right = null;
    newNode.left = null;
    size++;
    lastNode = newNode;
    newNode.parent = tempPointer;
    tempPointer.right = newNode;
}

It keeps saying termPointer can only be null at this location. I can't figure out why though.

This also fails:

newNode.parent = tempPointer.parent; //'tempPointer can only be null here'
tempPointer = newNode;

Upvotes: 1

Views: 726

Answers (2)

aldrin
aldrin

Reputation: 4572

You actually want a look ahead pointer that peeps to the right of the current node. Something like,

BinaryNode tempPointer = root;
lookaheadPointer = root;
while(lookaheadPointer != null) {
  tempPointer = lookaheadPointer;
  lookaheadPointer = tempPointer.right;
}

In your current code, the tempPointer is null at the end of the loop, as pointed out by @Julien

Upvotes: 2

Julien Lebosquain
Julien Lebosquain

Reputation: 41213

Your while loop will only end when tempPointer is null. You don't set tempPointer to any other value after the loop, so it will stay null until the end of the function.

Upvotes: 8

Related Questions