Home > database >  runtime error: member access within null pointer of type 'ListNode' - Clone a linked list
runtime error: member access within null pointer of type 'ListNode' - Clone a linked list

Time:03-16

I am trying to clone a linked list in reverse order.

    ListNode* cloneList(ListNode* head) {
        ListNode *prev = new ListNode(head->val);
        head = head->next;
        while (head != NULL)
        {
            ListNode *p = new ListNode(head->val, prev);
            head = head->next;
            prev = p;
        }
        return prev;
    }

The definition of ListNode is as follows :

struct ListNode
{
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};

But i am getting this runtime error : member access within null pointer of type 'ListNode'.

Am i making some mistake in creating or initialising the node? Please explain.

CodePudding user response:

It is unusual for a clone method to return a new list in reverse order, but OK, if that is your actual requirement.

As stated in comments, the code you have shown does not account for the possibility of the list being empty (ie, when head is nullptr), eg:

ListNode* cloneList(ListNode* head) {
    if (!head) return nullptr; // <-- add this
    ...
}

If head is not nullptr and points to a valid ListNode, and the list is properly null-terminated, then your code works just fine.

Online Demo

However, it can be simplified a bit, eg:

ListNode* cloneList(ListNode* head) {
    ListNode *newHead = nullptr;
    while (head) {
        newHead = new ListNode(head->val, newHead);
        head = head->next;
    }
    return newHead; 
}

Online Demo

  • Related