为什么我在尝试添加两个链表时出现此错误?

How come I am getting this error while trying to add two linked lists?

本文关键字:链表 两个 错误 添加 为什么      更新时间:2023-10-16

我正在尝试解决一个关于链表的实际编码问题,我应该在每个相应的节点中添加值以形成一个新的链表。但是我收到此错误:Line 13: Char 20: runtime error: member access within null pointer of type 'struct ListNode' (solution.cpp)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* nodes;
        nodes->val = l1->val + l2->val;
        nodes->next->val = l1->next->val + l2->next->val;
        nodes->next->next->val = l1->next->next->val + l2->next->next->val;
        return nodes;
    }
};

您必须先为 nodes 变量分配内存。

ListNode* nodes = new ListNode();

但是,如果您不再使用该变量,请不要忘记删除它,否则会出现内存泄漏。

未分配结果节点。

您正在访问 6 个指针,而不确保其中任何一个为非空。您需要检查 null

  • l1, l1->next, l1->next->next
  • l2, l2->next, l2->next->next

addTwoNumbers 实际上添加了 6 个数字。这不可能是对的。addTwoNumbers最多添加两个数字,或者调用您的方法addTwoLists

请记住,您的链表有一个结尾,因此此代码保证在最后两个元素中中断。

您需要重新考虑完整的方法。

正如在注释和答案中已经发现的那样,您不会为新节点分配内存。

但还有其他一些问题。您似乎假设两个列表都恰好包含三个节点。是什么让你如此肯定?如果其中一个列表更短或更长怎么办?

仍然不清楚:列表中第一个数字的含义是什么,最高或最低有效数字?这对您的算法外观有很大影响!

对于问题的其余部分,我将假设第一个数字是最不重要的数字,这种情况更容易处理:

ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
{
    ListNode* head = nullptr; // we want to return head of newly created list but
    ListNode* tail = nullptr; // need to append at its tail, so we need two pointers
    while(l1 && l2) // yet elements existing in both lists?
    {
        // need to create new nodes!
        ListNode* tmp = new ListNode(l1->val + l2->val);
        if(!tail)
        {
            // this will be the first node we create!
            head = tmp;
        }
        else
        {
            // we have a node already -> append
            tail->next = tmp;
        }
        // in any case, new tail is the newly created node
        tail = tmp;
        l1 = l1->next;
        l2 = l2->next;
    }
    // at this point, we worked through the common digits in both lists
    // we yet need to create copies for those digits yet remaining in
    // the longer of the two lists:
    while(l1)
    {
        // create copy of *l1 and append
        l1 = l1-> next;
    }
    while(l2)
    {
        // create copy of *l2 and append
        l2 = l2-> next;
    }
    // of course, only one of the loops can be entered at all...
    // be aware, though, that we might not have had elements in one of
    // the lists right at start, so head and tail still might be nullptr,
    // i. e. these two loops would look similar to the very first one!
    return head;
}

我们根本没有考虑的是溢出。您需要记住它是否发生,并在下一次循环运行中额外添加 + 1,如果是这样。