DSA-CRACKER icon indicating copy to clipboard operation
DSA-CRACKER copied to clipboard

in the Floyds_Cycle_Detection_Algorithm.cpp

Open 1RN21CS056 opened this issue 7 months ago • 0 comments

Instead of checking if (head == NULL) and then else if (head->next == head), you could directly combine these into one check for clarity:

if (head == NULL || head->next == head) return true;

Here's a slightly refined version

#include

using namespace std;

struct Node { int data; struct Node *next; Node(int x) { data = x; next = NULL; } };

class Solution { public: // Function to check if the linked list has a loop. bool detectLoop(Node *head) { if (head == NULL || head->next == head) return true;

    Node *slowPtr = head;
    Node *fastPtr = head->next;

    while (fastPtr != slowPtr) {
        if (fastPtr == NULL || fastPtr->next == NULL)
            return false;

        slowPtr = slowPtr->next;
        fastPtr = fastPtr->next->next;
    }

    return true;
}

};

1RN21CS056 avatar Jun 29 '24 10:06 1RN21CS056