Find length of loop in linked list - GeeksforGeeks

20 Oct, 2021
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
Java
Python3
C#
Javascript
// 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 node */struct 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 loopnodes in the list. If loop is not therein 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
// C program to count number of nodes// in loop in a linked list if loop is// present#include<stdio.h>#include<stdlib.h> /* Link list node */struct 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 program to test above function*/int 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;     printf("%d \n", countNodesinLoop(head));     return 0;}
// Java program to count number of nodes// in loop in a linked list if loop is// presentimport java.io.*; class GFG {      /* Link list node */static class Node{    int data;    Node next;    Node(int data)    {        this.data =data;        next =null;    }} // Returns count of nodes present in loop.static int countNodes( Node n){int res = 1;Node temp = n;while (temp.next != n){    res++;    temp = temp.next;}return res;} /* This function detects and counts loopnodes in the list. If loop is not therein then returns 0 */static int countNodesinLoop( Node list){    Node slow_p = list, fast_p = list;     while (slow_p !=null && fast_p!=null && fast_p.next!=null)    {        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;} static Node newNode(int key){    Node temp = new Node(key);         return temp;} /* Driver program to test above function*/    public static void main (String[] args) {        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;     System.out.println( countNodesinLoop(head));    }}// This code is contributed by inder_verma.
# Python 3 program to find the number# of nodes in loop in a linked list# if loop is present # Python Code to detect a loop and# find the length of the loop# Node defining classclass Node:         # Function to make a node    def __init__(self, val):        self.val = val        self.next = None     # Linked List defining and loop# length finding classclass LinkedList:         # Function to initialize the    # head of the linked list    def __init__(self):        self.head = None                    # Function to insert a new    # node at the end    def AddNode(self, val):        if self.head is None:            self.head = Node(val)        else:            curr = self.head            while(curr.next):                curr = curr.next            curr.next = Node(val)         # Function to create a loop in the    # Linked List. This function creates    # a loop by connecting the last node    # to n^th node of the linked list,    # (counting first node as 1)    def CreateLoop(self, n):                 # LoopNode is the connecting node to        # the last node of linked list        LoopNode = self.head        for _ in range(1, n):            LoopNode = LoopNode.next                     # end is the last node of the Linked List        end = self.head        while(end.next):            end = end.next                     # Creating the loop        end.next = LoopNode             # Function to detect the loop and return    # the length of the loop if the returned    # value is zero, that means that either    # the linked list is empty or the linked    # list doesn't have any loop    def detectLoop(self):                 # if linked list is empty then there        # is no loop, so return 0        if self.head is None:            return 0                 # Using Floyd’s Cycle-Finding        # Algorithm/ Slow-Fast Pointer Method        slow = self.head        fast = self.head        flag = 0 # to show that both slow and fast                 # are at start of the Linked List        while(slow and slow.next and fast and              fast.next and fast.next.next):            if slow == fast and flag != 0:                                 # Means loop is confirmed in the                # Linked List. Now slow and fast                # are both at the same node which                # is part of the loop                count = 1                slow = slow.next                while(slow != fast):                    slow = slow.next                    count += 1                return count                         slow = slow.next            fast = fast.next.next            flag = 1        return 0 # No loop     # Setting up the code# Making a Linked List and adding the nodesmyLL = LinkedList()myLL.AddNode(1)myLL.AddNode(2)myLL.AddNode(3)myLL.AddNode(4)myLL.AddNode(5) # Creating a loop in the linked List# Loop is created by connecting the# last node of linked list to n^th node# 1<= n <= len(LinkedList)myLL.CreateLoop(2) # Checking for Loop in the Linked List# and printing the length of the looploopLength = myLL.detectLoop()if myLL.head is None:    print("Linked list is empty")else:    print(str(loopLength)) # This code is contributed by _Ashutosh
// C# program to count number of nodes// in loop in a linked list if loop is// presentusing System; class GFG{     /* Link list node */    class Node    {        public int data;        public Node next;        public Node(int data)        {            this.data = data;            next = null;        }    }     // Returns count of nodes present in loop.    static int countNodes( Node n)    {        int res = 1;        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 */    static int countNodesinLoop( Node list)    {        Node slow_p = list, fast_p = list;         while (slow_p != null && fast_p != null &&                            fast_p.next != null)        {            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;    }     static Node newNode(int key)    {        Node temp = new Node(key);         return temp;    }     /* Driver code*/    public static void Main (String[] args)    {        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;         Console.WriteLine( countNodesinLoop(head));    }} // This code is contributed by Rajput-Ji
<script>// javascript program to count number of nodes// in loop in a linked list if loop is// present     /* Link list node */class Node {    constructor(data) {        this.data = data;        this.next = null;    }}     // Returns count of nodes present in loop.    function countNodes( n) {        var res = 1;         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     */    function countNodesinLoop( list) {        var slow_p = list, fast_p = list;         while (slow_p != null && fast_p != null && fast_p.next != null) {            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;    }     function newNode(key) {         temp = new Node(key);         return temp;    }     /* Driver program to test above function */              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;         document.write(countNodesinLoop(head)); // This code contributed by gauravrajput1</script>
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.
Related Articles:  
Detect loop in a linked list
Detect and Remove Loop in a Linked List
YouTubeGeeksforGeeks502K subscribersFind the length of loop in linked list | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:04•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=n6AMo1qFPlA" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Shubham Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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. 
subtleseeker
inderDuMCA
PriyaBadchariya
Leonardo_Da_Vinci
Rajput-Ji
SHUBHAMSINGH10
andrew1234
GauravRajput1
sweetyty
simranarora5sos
Adobe
Qualcomm
Linked List
Adobe
Qualcomm
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
LinkedList in Java
Doubly Linked List | Set 1 (Introduction and Insertion)
Linked List vs Array
Delete a Linked List node at a given position
Merge two sorted linked lists
Implementing a Linked List in Java using Class
Queue - Linked List Implementation
Implement a stack using singly linked list
Circular Linked List | Set 1 (Introduction and Applications)
Find Length of a Linked List (Iterative and Recursive)