Skip to content

in the Floyds_Cycle_Detection_Algorithm.cpp #80

@1RN21CS056

Description

@1RN21CS056

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;
}

};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions