We can detect whether there is any loop in the Linked List by
Create two references - \( slow \) and \( fast \).
Start from the beginning of the list. \( slow \) hops one node while \( fast \) hops two.
If they meet, loop is found.
publicbooleanhasLoop(Node first){
/* Linked List doesn't exist - so no loop */ if(first ==null) returnfalse;
/* Create two reference */ Node slow, fast;
/* Both start from the beginning of the Linked List */ slow = fast = first; while(true){ /* One hop */ slow = slow.next; if(fast.next!=null) /* Two hops */ fast = fast.next.next; else returnfalse;
/* If slow or fast either hits null - no loop */ if(slow ==null|| fast ==null) returnfalse;
/* if slow and fast meet - Bingo! loop found */ if(slow == fast) returntrue; } }