Saturday, December 4, 2021
HomeTop Coding Questionwrite a program to find length of cycle of loop .

write a program to find length of cycle of loop .

Given a linkedlist,we have to find the length of cycle in a linkedlist

Logic:

STEP 1:start traversing a linkedlist,if we detect loop .
STEP 2:then maintain count variable to count the loop length

Code

int Lengthloop(Node * head)  
{  
     
    struct Node *tmp = head;  
    int count=1;
    while (temp->next != head)  //checking how many node are in loop.
    {  
          count++; 
        temp = temp->next;  
    }  
    return count;  
}  

Ouput:

2

Time Complexity:O(N)

Space Complexity:O(1)

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments