7/7/2018 - 4:31 AM

Find length of loop in linked list

We know that Floyd’s Cycle detection algorithm terminates when fast and slow pointers meet at a common point. We also know that this common point is one of the loop nodes. We store the address of this in a pointer variable say ptr2. Then we start from the head of the Linked List and check for nodes one by one if they are reachable from ptr2. When we find a node that is reachable, we know that this node is the starting node of the loop in Linked List and we can get pointer to the previous of this node.

using namespace std;

struct linked_list {
    int data;
    struct linked_list* next;
typedef struct linked_list node;

node* insert(node* head, int n) {
    node* list = (node*)malloc(sizeof(node*));
    return head;

int CountLoop (node* n) {
    int len = 1;
    node* temp = n;
    while (temp->next != n){
        temp = temp->next;
    return len;

int DetectLoop (node* head) {
    node *slow=head, *fast=head,*ptr;
    while (slow && fast && fast->next) {
        slow = slow->next;
        fast = fast->next->next;

        if (slow == fast)
            return CountLoop (slow);

int main() {
    int n;
    node* head = NULL;
    while (true) {
        cout<< "Enter the element, enter -9 to stop: ";
        if (n==-9)
            head = insert(head,n);
    head->next->next->next->next->next = head->next;
    cout<< "Length of Loop is " << DetectLoop(head);