Write a simple code to identify loop or cycle in a linked list.
In general, the last node is null in a Linked list. A loop/cycle exists in a LinkedList when no null is
reached as we traverse throughout the LinkedList.
There are various ways to identify loop/cycle in a linked list.
The below diagram illustrates linked list loop/cycle:

Approach 1: Using Hashing
- Traverse the linked list nodes and keep adding the node addresses in a Hash Table.
- At any point, if NULL is reached then the loop/cycle doesnot exist, return false.
- If next of current node points to any of the previously stored nodes in Hash Table, then return true.
The disadvantage with above approach is it requires extra storage to keep track of hashes.
Approach 2: Floyd’s Cycle-Finding Algorithm
- Traverse linked list nodes using two pointers.
- Move first pointer by one step and second pointer by two step.
- If the pointers meet at the same node then there is a loop.
- At any point, if NULL is reached then the loop/cycle doesnot exist, return false.
|