why this printf statement in the last of function is Not getting printed?

Viewed 36

I wrote a simple algorithm to detect loop in a singly linked list,it worked correctly for a looped list. But in case of list with no Loop, After executing while loop, printf function is not printing in last statement of given code.

This is a part of code:-

   //Detacting a loop in singally linked list Using Fast(2x) and Slow (1x) traversal;
    void DetactLoop(struct Node **head)
    {
        struct Node *Fast = *head;
        struct Node *Slow = *head;
        if (Fast == NULL)
        {
            printf("Head is NULL");
            return;
        }
        while (Fast != NULL || Fast->next != NULL)
        {
            Fast = Fast->next->next;
            Slow = Slow->next;
            if (Fast == Slow)
            {
                printf("Loop detected!");
                return;
            }
        }
        printf("No Loop found!");
    }
1 Answers

The loop while (Fast != NULL || Fast->next != NULL) will continue when Fast is not NULL and Fast->next is NULL. Then NULL is dereferenced at Fast = Fast->next->next; and an undefined behavior is invoked, typically leading to Segmentation Fault.

The loop should be while (Fast != NULL && Fast->next != NULL). You should use AND, not OR.

Related