Given a Linked List, check if the linked list has a loop or not.
There are various methods shown here: Detect Cycle in Linked List
Ouput: No loop is detected.
While traversing the linked list we reached the end of linked list. Therefore no loop is present in linked list.
Ouput: 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)
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Detect loop in a linked list
- Detect and Remove Loop in a Linked List
- Detect cycle in the graph using degrees of nodes of graph
- Create new linked list from two given linked list with greater element at each node
- Convert singly linked list into circular linked list
- Merge a linked list into another linked list at alternate positions
- XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
- Difference between Singly linked list and Doubly linked list
- XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
- Convert Singly Linked List to XOR Linked List
- Check if a linked list is Circular Linked List
- Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common nodes
- Create a linked list from two linked lists by choosing max element at each position
- Construct a Doubly linked linked list from 2D Matrix
- Partitioning a linked list around a given value and If we don't care about making the elements of the list "stable"
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.