Question about Linked Lists (indexOf method)

public int indexOf(int item) {
int index = 0;
var current = first;
while (current != null) {
if (current.value == item) return index;
current = current.next;
index++;
}
return -1;
}

Given the above code, I have a question regarding the bolded line.
Is a node considered null as long as it doesn’t point to another node, even if it’s value field has data?

Would the code still function the same if I replace that line with
while (current.next != null) ?

SHORT ANSWER:
A Node where node.next == null is the last Node in your linked list.
If you replace the conditional, and look for the last Node’s value, then -1 will be returned.
Also, if the list is empty, then there will be a runtime error (crash)

LONG ANSWER:
Lets say we have the list:
first → Node 10, next → Node 20, next → Node 30, null
Go ahead and replace the conditional with (current.next != null) and look for 30.
System.out.println(list.indexOf(30));
-1 // will be printed

When the conditional gets to Node 30, null
while (current.next != null) will execute
while (null != null) and the loop will exit before it can inspect Node 30, null

When we use the original conditional and look for 30, then
while (current != null) will execute
while (memory location of Node[30,null] != null) // will be TRUE, then within the body
if (current.vaule == item) return index;
if (30 == 30) return 2;

If the list is empty, then
while (current.next != null) will try to execute
while (null.next != null) which will crash.

HINT
When I’m writing code in C++ or Java, I always ask myself:
Is there memory allocated for the variable(s) in this line of code?

2 Likes

Thank you for the response, I appreciate both the long & short answers.

So essentially current.next != null will stop when at the last node, exiting the loop before it can execute the code on that last node, whereas current != null would have continued the iteration on all nodes, but not entering the loop again because current is now null (technically no longer even a node).