【问题标题】:runtime error: member access within null pointer of type 'ListNode'运行时错误:“ListNode”类型的空指针内的成员访问
【发布时间】:2021-05-02 09:21:35
【问题描述】:

我花了很多时间在上面,但仍然遇到同样的错误。请有人帮忙。 我已经为一个 leetcode 问题编写了这段代码。(合并两个链表) 看了很多类似的答案,还是想不通

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

【问题讨论】:

  • 例如假设 l1 和 l2 等于 NULL。你能明白为什么你的函数会在这种情况下崩溃吗?实际上,如果 l1 或 l2 等于 NULL,你会遇到同样的崩溃。

标签: c++ linked-list runtime-error nodes


【解决方案1】:

如果两个输入均非空,则仅将 last 设置为非空值。

你需要先检查它,例如

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-27
    • 1970-01-01
    • 2022-12-19
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多