简体   繁体   中英

runtime error: member access within null pointer of type 'ListNode'

I have spent a lot of time on it but still getting the same error. Please someone help. I have written this code for a leetcode question.(merging two linked lists) have read many similar answers but still cannot figure out

class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2)
    {
        ListNode* third = NULL;
        ListNode* last = NULL;
        if (l1 && l2) {
            if (l1->val < l2->val) {
                third = last = l1;
                l1 = l1->next;
                last->next = NULL;
            }
            else {
                third = last = l2;
                l2 = l2->next;
                last->next = NULL;
            }
        }

        while (l1 && l2) {
            if (l1->val < l2->val) {
                last->next = l1;
                last = l1;
                l1 = l1->next;
                last->next = NULL;
            }
            else {
                last->next = l2;
                last = l2;
                l2 = l2->next;
                last->next = NULL;
            }
        }

        if (l1) {
            last->next = l1;
        }

        if (l2) {
            last->next = l2;
        }

        return third;
    }
};

You only set last to a non-null value if both inputs are non-null.

You need to check it first, for instance with

if (last)
{
    last->next = l1 ? l1 : l2;
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM