Output: No loop is detected.
While traversing the linked list we reached the end of linked list. Therefore no loop is present in linked list.
Output: Loop detected.
While traversing the linked list we reached the node with value 10 is linked with the head node which depicts a loop in the linked list. Therefore loop is present in linked list.
- Create a map which will store the visited node in linked list.
- Traverse the linked list and do the following:
- Check whether the current node is present in the map or not.
- If the current node is not present in the map then, insert the current node in the map.
- If the Node is present in the map, the loop in a linked list is detected.
- If we reached to Null Node while traversing the linked list then, the given linked list has no loop present in it.
Below is the implementation of above approach:
Time Complexity: O(N*log N)
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.