We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
I know why.i.e. because there comes a point when you fast->next becomes 0 and you are still doing fast->next->next.
A goof solutin to itis to just do fast->next->next only when fast->next != 0, and return 0 if fast->next is 0. You can see this in the code below. I hope it helps.
bool has_cycle(Node* head) {
bool ans;
if (head == 0) {
return 0;
}
if (head == head->next) {
return 1;
}
Node* tempHead = head;
Node* slow = head;
Node* fast = head->next;
while (tempHead->next != NULL) {
slow = slow->next;
if (fast->next == 0) {
return 0;
}
fast = fast->next->next;
if (slow == fast) {
return 1;
}
tempHead = tempHead->next;
}
return 0;
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Linked Lists: Detect a Cycle
You are viewing a single comment's thread. Return to all comments →
I know why.i.e. because there comes a point when you fast->next becomes 0 and you are still doing fast->next->next.
A goof solutin to itis to just do fast->next->next only when fast->next != 0, and return 0 if fast->next is 0. You can see this in the code below. I hope it helps.
bool has_cycle(Node* head) {
}