I am implementing a stack using linked list in java. The problem is that I get a nullPointerException when there is no element below, e.g. the StackNode.link does not exist. Therefore if I try assigning the StackNode.link I get the Exception.
Using an if statement to only run the code if it exists, I just get the Exception in the if statement. How do I go about this?
int pop() {
StackNode temp = top;
// update top
top = belowTop;
belowTop = top.link; // this is where I get the nullPointExcpetion
return temp.data;
}
I would expect that when top.link does not exist (e.g. is null) then belowTop would just be null. This would be fine, but as described I get the exception.
EDIT: This is what I tried with the if-statement
if (top.link != null) {
belowTop = top.link;
}
Aucun commentaire:
Enregistrer un commentaire