Reputation: 1249
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head == NULL) return false;
ListNode* walker = head;
ListNode* runner = head;
while(runner->next != NULL && walker->next != NULL){
walker = walker->next;
runner = runner->next->next;
if(walker == runner) return true;
}
return false;
}
};
I was practicing an interview code which seemed to be pretty simple. I have to return a bool that determines whether or not the singly-linked list has a cycle. I made two pointers walker which moves 1 step and runner which moves 2 steps every iteration.
But then this code gave me an error:
Line 15: member access within null pointer of type 'struct ListNode'
What causes that error?
Upvotes: 24
Views: 116924
Reputation: 1
//- If a loop from circular path then there is hundred% chance that they will going to meet at some point so here we are taking a walker which move one step and a runner which move two step.
bool hasCycle(ListNode *head){
if(head == NULL || head->next == NULL)
return false;
struct ListNode *temp = head;
struct ListNode *walker;
struct ListNode *runner;
walker = runner= head;
while(temp ){
walker = walker->next;
runner = runner->next->next;
if(runner == walker) // as soon both get at same address we got return as
true value.
{ return True; }
temp = temp->next;
}
return false;
}
Upvotes: 0
Reputation: 159
Sort answer is here with explanation
It returns the error because
runner=runner->next->next
can be NULL and you are checking runner->next!=NULL in while conditioning so you have to do a little change In your code In order to get your answer In while condition check forrunner->next->next!=NULL
and get the right answer.
Upvotes: 0
Reputation: 312
The Below Code should work fine.
It is the classic Hare-Tortoise theorem, where the hare takes 2 steps(distance units) while the tortoise goes by 1.
I think you did not check the nullity of runner->next->next
which has caused this error
bool hasCycle(ListNode *head)
{
if(head == NULL || head->next == NULL)
{
return false;
}
ListNode* tortoise=new ListNode();
ListNode* hare = new ListNode();
tortoise=head;
hare=tortoise->next;
while(tortoise != hare)
{
if(hare == NULL || hare->next == NULL)
{
return false;
}
tortoise=tortoise->next;
hare=hare->next->next;
}
return true;
}
Upvotes: 0
Reputation: 8186
This should solve it:
bool hasCycle(ListNode *head) {
if(head == NULL || head->next == NULL) { return false; }
struct ListNode * walker = new ListNode(1);
struct ListNode * runner = new ListNode(2);
walker = head;
runner = walker->next;
while(walker != fast){
if(runner == NULL || runner->next == NULL) { return false; }
walker = walker->next;
runner = runner->next->next;
}
return true;
}
Upvotes: 0
Reputation: 37579
You only make sure that runner->next
is not null, however after assignment
runner = runner->next->next;
runner
can become null.
Upvotes: 28