Search code examples
c++data-structureslinked-list

member access within null pointer of type 'struct ListNode'


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?


Solution

  • You only make sure that runner->next is not null, however after assignment

    runner = runner->next->next;

    runner can become null.