为什么我在尝试添加两个链表时出现此错误?
How come I am getting this error while trying to add two linked lists?
我正在尝试解决一个关于链表的实际编码问题,我应该在每个相应的节点中添加值以形成一个新的链表。但是我收到此错误: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,如果是这样。
相关文章:
- 如何使用模板元编程在自由函数C++链接两个不相关的类
- 链接两个使用 c++ 构建的库_static
- 当我链接两个静态C++库时,我可以在两个主函数库中有两个主要功能吗?
- 在链接到两个 exe 的 dll 中共享全局变量
- 如何链接两个LLVM位码模块?
- 在没有额外代码的情况下链接两个独立类的最通用方法是什么?
- 在 Linux 上的 Visual Studio 中链接两个项目
- 在同一C++项目中链接两个不同版本的 protobuf 库
- 如何链接两个ArUco标记的姿势
- CMakeLists配置以链接两个C++项目
- 如何静态链接到两个版本的 xerces-c(或任何与此相关的库)
- Xcode 不链接两个结构
- 如何在 C/C++ 中链接两个 .so
- 链接两个具有相同函数签名的强函数符号的结果使用 G++ 以及原因
- 在 Visual Studio 解决方案中链接两个项目
- 链接两个枚举类型成员
- OpenGL - 链接两个纹理不起作用
- 我如何使用cmake链接两个库到我的程序
- 当链接到两个第三方共享库时,c++程序崩溃
- 在链接两个对象文件时,使用#ifndef防止定义一个函数两次