Detect loop in a linked list ?
- There are two ways to detect loop in linked list or not.
Method 1:
- Traverse through each node till end , tracking visited node using Hash map.
- If you find node that is already visited, then there is a loop in LinkedList
- If you reach till end while traversing then there is no loop in LinkedList
Output:
Loop found
Method 2:
- Efficient approach for this problem would be Floyd’s cycle detection algorithm, so steps for this algorithm would be:
-
- Use two pointer fastPtr and slowPtr and initialize both to head of linkedlist
- Move fastPtr by two nodes and slowPtr by one node in each iteration.
- If fastPtr and slowPtr meet at some iteration , then there is a loop in linkedlist.
- If fastPtr reaches to the end of linkedlist without meeting slow pointer then there is no loop in linkedlist (i.e fastPtr->next or fastPtr->next->next become null).