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;
}
No comments:
Post a Comment