DSA-CRACKER
DSA-CRACKER copied to clipboard
in the Floyds_Cycle_Detection_Algorithm.cpp
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;
}
};