I have a faster way to find if a list is circular linked list, in contrast to the solution that Cracking the Coding Interview has offered:
In the below algorithm, fast-pointer
will either hit null (in case of linear list) or hit starting point/origin (in case of circular) quicker than conventional (fast & slow pointer approach).
Reason: because in fast & slow pointer approach, we wait for the fastPointer == slowPointer
condition to determine if it's a circular list. But fastPointer
would reach its origin/starting point first before hitting slow pointer. (what's the point of crossing over the starting point and continuing the hunt for slowPointer
?)
Isn't the below example a better algorithm? If so, then why have a fast & slow pointer approach?
(I didn't consider starting point as "node outside of loop" scenario while asking question.)
public boolean findCircular(Node someRandomNodeOfList) {
Node fast = someRandomNodeOfList;
while (true) {
if ((fast.next == null) || (fast.next.next == null)) {
return false;
}
else if (fast.next == someRandomNodeOfList|| fast.next.next == someRandomNodeOfList) {
return true;
}
else {
fast = fast.next.next;
}
}
return false;
}