Wednesday, April 17, 2019

Find the Length of Loop in Linked List




We modify the Floyd's Loop/Cycle Detection Algorithm that we saw in the previous Post to find the count of Nodes which are part of the Linked List.

int count_loop_lenth(Node *node){
    int count = 1;
    Node *curr = node;
    while(curr->next != node){
        curr = curr->next;
        ++count;
    }
    return count;
}

int detect_loop_floyd(Node *head){
    Node *slow = head;
    Node *fast = head;
    while(slow && fast && fast->next){
        slow = slow->next;
        fast = fast->next->next;
        if(slow == fast){
            return count_loop_lenth(slow);
        }
    }
    return 0;
}

Watch detailed Explanation on Youtube.


Subscribe to KnowledgeCenter


No comments:

Post a Comment

LeetCode 30 Day Challenge | Day 7 | Counting Elements

Given an integer array  arr , count element  x  such that  x + 1  is also in  arr . If there're duplicates in  arr , count them sepe...