Reputation: 220
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;
}
else {
belowTop = null;
}
Upvotes: 0
Views: 439
Reputation: 26926
You need to check if the variable top
has been initialized or not:
...
if (top != null) {
belowTop = top.link;
} else {
// Handle the not initialized top variable
}
...
Probably a good solution is to throw a runtime exception if belowTop
if not initialized, like
...
if (top == null) {
throw new IllegalStateException("Can't pop from an empty stack");
}
belowTop = top.link;
...
In this case you have to prepare also a method that gives the ability to check if the stack is not empty or not initialized. Here a complete proposal:
public boolean isEmpty() {
// Your logic here
}
// Better have a public access because it seems an utility library and
// it should be accessed from anywhere
public int pop() {
StackNode temp = top;
// update top
top = belowTop;
if (top == null) {
throw new IllegalStateException("Can't pop from an empty stack");
}
belowTop = top.link; // Now it works
return temp.data;
}
And you can use it as follow:
if (!myStack.isEmpty()) {
int value = myStack.pop();
// Do something
}
Upvotes: 2
Reputation: 340
Give this one a shot:
if (top.link != null) {
belowTop = top.link;
} else {
//handle the exception
}
The above checks if the top.link is null, which is a valid check and won't cause a nullPointerException.
Upvotes: 0