Write a function detectAndCountLoop() that checks whether a given Linked List contains loop and if loop is present then returns count of nodes in loop. For example, loop is present in below linked list and length of loop is 4. If loop is not present, then function should return 0.
We know that Floyd’s Cycle detection algorithm terminates when fast and slow pointers meet at a common point. We also know that this common point is one of the loop nodes (2 or 3 or 4 or 5 in the above diagram). We store the address of this common point in a pointer variable say ptr. Then we initialize a counter with 1 and start from the common point and keeps on visiting next node and increasing the counter till we again reach the common point(ptr). At that point, the value of the counter will be equal to the length of the loop.
This article is contributed by Shubham Gupta. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Find first node of loop in a linked list
- Find Length of a Linked List (Iterative and Recursive)
- Detect loop in a linked list
- Detect and Remove Loop in a Linked List
- Make a loop at k-th position in a linked list
- Check linked list with a loop is palindrome or not
- Length of longest palindrome list in a linked list using O(1) extra space
- Check whether the length of given linked list is Even or Odd
- Find the sum of last n nodes of the given Linked List
- Find a peak element in Linked List
- Find unique elements in linked list
- Find the middle of a given linked list in C and Java
- Find the product of last N nodes of the given Linked List
- Find pairs with given sum in doubly linked list
- Find the fractional (or n/k - th) node in linked list