Reputation: 19612
I have a linked list in which first node contains null object. means firstNode.data is equal to null, firstNode.nextPointer = null, firstNode.previousPointer = null.
And I want to check if firstNode is null or not. So I tried-
if(list.firstNode == null){
//do stuff
}
but this doesn't works?
I also tried equals too. Any suggestions?
I tried printing. And I got as-
{null} -- firstNode
Upvotes: 6
Views: 63220
Reputation:
You can check if all the fields of the node are null:
Node firstNode = list.firstNode;
if(firstNode.data == null &&
firstNode.nextPointer == null &&
firstNode.previousPointer == null) {
//Do stuff
}
Or to prevent code repetition, you can either create an instance method isNull() to do the test or create a NULL object and override the equals method in your Node class to check if a node is equal to the null node as you described.
class Node<E> {
//The null node, assuming your constructor takes all three values.
public static final Node NULL = new Node(null, null, null);
//Fields here with constructors etc.
@Override
public void equals(Object obj) {
if(!obj instanceof Node) return false;
Node<?> node = (Node<?>)obj;
if(node.data.equals(this.data) &&
node.nextPointer == this.nextPointer &&
node.previousPointer == this.previousPointer) {
return true;
} else {
return false;
}
}
Then when you want to check if a node is null you can do:
if(list.firstNode.equals(Node.NULL)) {
//Do stuff
}
Upvotes: 0
Reputation: 54074
It seems to me that your question is related to the processing of a doubly-linked list.
To check if empty use: (list.firstNode.next == list.firstNode.previous)
this is true
for an empty doubly linked list.
Upvotes: 0
Reputation: 21409
The answer is in the question. You said:
have a linked list in which first node contains null object. **means firstNode.data is equal to null**,
This means you should do the following instead:
if(list.firstNode.data == null){
//do stuff
}
Upvotes: 0
Reputation: 424953
I think your firstNode
is not null
, but its fields are. Try something like this:
if (list.firstNode.data == null) {
//do stuff
}
Upvotes: 13
Reputation: 21572
You checking for list.firstNode being null. Do you mean to check for
list.firstNode.data==null
Upvotes: 0