开发者

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 = tempPo开发者_如何学编程inter.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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜