Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

in the Floyds_Cycle_Detection_Algorithm.cpp #80

Open
1RN21CS056 opened this issue Jun 29, 2024 · 0 comments
Open

in the Floyds_Cycle_Detection_Algorithm.cpp #80

1RN21CS056 opened this issue Jun 29, 2024 · 0 comments

Comments

@1RN21CS056
Copy link

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

};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant