【发布时间】:2021-01-13 03:22:38
【问题描述】:
我得到了两个非空链表,代表两个非负整数,我试图将这两个数字相加并将总和作为链表返回。 我收到一个错误提示
字符 18:运行时错误:“ListNode”类型的空指针内的成员访问 (solution.cpp) 总结:UndefinedBehaviorSanitizer:未定义行为
为什么我会得到这个数组,我该如何解决这个问题?
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int carry=0,sum = 0;
ListNode* res = new ListNode(0);
while(l1->next !=NULL){
sum = carry + l1->val + l2->val;
if(sum>9)
carry = 1;
else
carry = 0;
res = res->next;
res->val = sum;
}
return res;
}
};
错误显示在 Line with code 中
res->val = sum;
【问题讨论】:
-
小测验:什么是“
ListNode* res = new ListNode(0);”?res->next;会在这里做什么?当res=res->next;时,您期望会发生什么?你试过explaining every line of your program to your rubber duck吗? -
另外请尝试向你的橡皮鸭解释循环
while(l1->next !=NULL),并告诉它你在哪里修改l1。
标签: c++ pointers linked-list runtime-error