Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
244 views
in Technique[技术] by (71.8m points)

c++ - 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;
    }
};
question from:https://stackoverflow.com/questions/65937821/runtime-error-member-access-within-null-pointer-of-type-listnode

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
} 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...