Write a program that checks whether a given Linked List contains a loop and if a loop is present then returns the count of nodes in the loop. For example, a loop is present in the below-linked list and the length of the loop is 4. If the loop is not present, then the function should return 0.
Below is the step-by-step approach:
- Traverse every node of the linked list and maintain the position starting with one. Increment the position after every node.
- Check whether that node is present in the Map or not.
- If the map does not contain the address of that node, insert it into the map along with its position.
- If the map already contains the address of that node, return the difference between their positions.
- If no such node has been found, return 0.
Below is the implementation of the above approach:
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.
- Find length of loop in linked list
- Adding two polynomials using Linked List using map
- Find first node of loop in a linked list
- Detect Cycle in a Linked List using Map
- Check linked list with a loop is palindrome or not
- Detect loop in a linked list
- Make a loop at k-th position in a linked list
- Detect and Remove Loop in a Linked List
- Length of longest palindrome list in a linked list using O(1) extra space
- XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
- XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
- Merge a linked list into another linked list at alternate positions
- Convert singly linked list into circular linked list
- Difference between Singly linked list and Doubly linked list
- Convert Singly Linked List to XOR Linked List
- Create new linked list from two given linked list with greater element at each node
- Check if a linked list is Circular Linked List
- Generate Linked List consisting of maximum difference of squares of pairs of nodes from given Linked List
- Find Length of a Linked List (Iterative and Recursive)
- Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common nodes
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.
Improved By : adityapande88