So I've been programming for a few years mostly as an amateur/student, and I'm aware of the fact that using exceptions is generally frowned upon when used as a lack of consideration for input and just a catch-all (e.g., lazy programming). But I have a specific question regarding a programming interview question:
Given a linked list, find if there is a cycle in it.
The solution being to use two pointers, iterate the first by 1 and the second by 2 positions, and if they ever meet then there is a cycle. If you get a null pointer then there is no cycle.
In the context of an interview, if I wrote the following code saying something like:
"I'm aware that this may not be the best use of exceptions, but since a NullPointerException specifically is the exit condition, it seems the best way to just leverage the language in order to get what I want in an expeditious way. In this way I'm leveraging exceptions in order to check null input, as well as for the exit condition of reaching the end of the list."
Would this be acceptable? Or would this be considered lazy?
boolean hasCycle(Node head) {
try{
Node start = head;
Node runner = head;
do{
start = start.next;
runner = runner.next.next;
if(start == runner) {
return true;
}
}while(runner != start) ;
}
catch(NullPointerException ex){
return false;
}
return false;
}