Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

runtime error: member access within null pointer of type 'ListNode' – Clone a linked list

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’.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading