简体   繁体   中英

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;

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM