【发布时间】:2016-12-07 14:59:27
【问题描述】:
2。添加两个数字
给定两个链表,表示两个非负数。这些数字以相反的顺序存储,它们的每个节点都包含一个数字。将两个数字相加并作为链表返回。
输入:
(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
我已经完成了 Leetcode 中第二个问题的代码。当我提交答案时,当输入为两个零时,我遇到了运行时错误。但是当我使用我自己的自定义测试用例时,它似乎工作得很好。
我已经非常仔细地检查了我的代码,仍然找不到错误所在。你能帮我解决这个问题吗?
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
struct ListNode* p1;
struct ListNode* p2;
struct ListNode* head;
head = (struct ListNode*)malloc(sizeof(struct ListNode*));
struct ListNode* cur = head;
p1 = l1; p2 = l2;
int sum, carry = 0, x, y;
while(p1 || p2)
{
//Assign the values of the listnode to x and y.
if(p1 != NULL) x = p1 -> val; else x = 0;
if(p2 != NULL) y = p2 -> val; else y = 0;
sum = x + y + carry;
//Declare a new node nxt(next) and insert it after the current node
struct ListNode* nxt;
nxt = (struct ListNode*)malloc(sizeof(struct ListNode*));
nxt -> val = sum % 10;
carry = sum / 10;
cur -> next = nxt;
cur = cur -> next;
if(p1 != NULL) p1 = p1 -> next;
if(p2 != NULL) p2 = p2 -> next;
}
if(carry > 0)
{
struct ListNode* nxt;
nxt = (struct ListNode*)malloc(sizeof(struct ListNode*));
nxt -> val = carry;
cur -> next = nxt;
}
head = head -> next;
return head;
}
错误:
自定义测试用例:
【问题讨论】:
-
(struct ListNode*)malloc(sizeof(struct ListNode*))应该是malloc(sizeof(struct ListNode))。您需要为ListNode分配足够的空间,而不是指向一个的指针。在 C 中省略malloc()的强制转换是一种很好的风格。 -
如果您想确保两个节点都存在,请将
while(p1 || p2)替换为while(p1 && p2),之后不要检查(p1 != NULL)或(p2 != NULL)。 -
您的列表不是 NULL 终止的。你也有内存泄漏。
-
那么如何编辑代码呢?
标签: c linked-list