-
Notifications
You must be signed in to change notification settings - Fork 65
Open
Description
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;
}
};
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels