【发布时间】:2021-04-01 03:53:17
【问题描述】:
关于 Leetcode 的问题 2:
添加两个数字。
我的代码在这里:
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
struct ListNode* result;
volatile bool carry = false;
while ((l1 != NULL) || (l2 != NULL) ) {
result = (struct ListNode*)malloc(sizeof(struct ListNode) );
result->next = NULL;
int v1 = 0;
if (l1 != NULL) {
v1 = l1->val;
l1 = l1->next;
}
int v2 = 0;
if (l2 != NULL) {
v2 = l2->val;
l2 = l2->next;
}
int sum = v1 + v2;
if (carry == true)
sum += 1;
carry = (sum > 9);
result->val = sum%10;
printf("result->val: %d, sum: %d, carry: %d\n",result->val,sum,carry);
//result = result->next;
}
return result;
}
输入
[2,4,3]
[5,6,4]
期待
[7,0,8]
标准输出
result->val: 7, sum: 7, carry: 0
result->val: 0, sum: 10, carry: 1
result->val: 8, sum: 8, carry: 0
真的出来了:
[8]
我觉得可能是损失
result = result->next;
在while循环中,
所以我在printf()之后添加它。
但输出似乎为空
[]
我的代码有什么问题?
【问题讨论】:
-
进行基本调试。使用调试器单步执行代码并在运行时对其进行检查。如果您在这里仍然需要帮助,请提供可以重现问题的最少完整代码。见:How to create a Minimal, Reproducible Example
-
我们无权访问 leetcode 测试。您需要显示构造传递给函数的链表的代码。
-
result = (struct ListNode*)malloc(sizeof(struct ListNode) );你每次都在覆盖头节点。使用两个变量 - 一个用于头节点(要返回),一个用于最后一个节点(用于添加下一个节点)。 -
因为
result->next在每次迭代中都变成NULL,运行result = result->next;只会使result等于NULL。 -
基本上你失去了链表的头部:(
标签: c linked-list