C++ Program For Finding The Length Of Loop In Linked List - GeeksforGeeks

05 Apr, 2022
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, the loop is present in below-linked list and length of the loop is 4. If the loop is not present, then the function should return 0.
Approach: It is known that Floyd’s Cycle detection algorithm terminates when fast and slow pointers meet at a common point. It is also known that this common point is one of the loop nodes. Store the address of this common point in a pointer variable say (ptr). Then initialize a counter with 1 and start from the common point and keeps on visiting the next node and increasing the counter till the common pointer is reached again. At that point, the value of the counter will be equal to the length of the loop.Algorithm:
Find the common point in the loop by using the Floyd’s Cycle detection algorithmStore the pointer in a temporary variable and keep a count = 0Traverse the linked list until the same node is reached again and increase the count while moving to next node.Print the count as length of loop
Find the common point in the loop by using the Floyd’s Cycle detection algorithm
Store the pointer in a temporary variable and keep a count = 0
Traverse the linked list until the same node is reached again and increase the count while moving to next node.
Print the count as length of loop
C++
// C++ program to count number of nodes// in loop in a linked list if loop is// present#include<bits/stdc++.h>using namespace std; // Link list nodestruct Node{    int data;    struct Node* next;}; // Returns count of nodes present// in loop.int countNodes(struct Node *n){    int res = 1;    struct Node *temp = n;    while (temp->next != n)    {        res++;        temp = temp->next;    }    return res;} /* This function detects and counts loop   nodes in the list. If loop is not there   in then returns 0 */int countNodesinLoop(struct Node *list){    struct Node *slow_p = list,                *fast_p = list;     while (slow_p &&           fast_p &&           fast_p->next)    {        slow_p = slow_p->next;        fast_p = fast_p->next->next;         /* If slow_p and fast_p meet at           some point then there is a loop */        if (slow_p == fast_p)            return countNodes(slow_p);    }     /* Return 0 to indicate that       there is no loop*/    return 0;} struct Node *newNode(int key){    struct Node *temp =           (struct Node*)malloc(sizeof(struct Node));    temp->data = key;    temp->next = NULL;    return temp;} // Driver Codeint main(){    struct Node *head = newNode(1);    head->next = newNode(2);    head->next->next = newNode(3);    head->next->next->next = newNode(4);    head->next->next->next->next = newNode(5);     // Create a loop for testing    head->next->next->next->next->next = head->next;     cout << countNodesinLoop(head) << endl;    return 0;}// This code is contributed by SHUBHAMSINGH10
Output:
4
Complexity Analysis:
Time complexity:O(n). Only one traversal of the linked list is needed.
Auxiliary Space:O(1). As no extra space is required.
Please refer complete article on Find length of loop in linked list for more details!
simranarora5sos
Adobe
Linked Lists
Qualcomm
C++
C++ Programs
Linked List
Adobe
Qualcomm
Linked List
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Header files in C/C++ and its uses
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
C++ Program for QuickSort
Sorting a Map by value in C++ STL