
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
if(!l1 || !l2) {
return NULL;
}
struct ListNode * ret = (struct ListNode *)calloc(1, sizeof(struct ListNode));
int lastnum = 0;
struct ListNode * result = ret;
while (l1 != NULL || l2 != NULL) {
int val1 = l1 != NULL ? l1->val : 0;
int val2 = l2 != NULL ? l2->val : 0;
ret -> val = (val1 + val2 + lastnum) % 10;
printf("val:%d \n", ret -> val);
lastnum = (val1 + val2 + lastnum) / 10;
if (l1) l1 = l1->next;
if (l2) l2 = l2->next;
if (l1 != NULL || l2 != NULL) {
struct ListNode * next = (struct ListNode *)calloc(1, sizeof(struct ListNode));
ret->next = next;
ret = ret->next;
}
}
if (lastnum) {
struct ListNode * next = (struct ListNode *)calloc(1, sizeof(struct ListNode));
next->val = lastnum;
printf("val:%d \n", next->val);
ret->next = next;
}
return result;
}

int getlength(struct ListNode* node)
{
if (!node) {
return 0;
}
int length = 0;
while (node) {
length++;
node= node->next;
}
return length;
}
static struct ListNode* extendList(struct ListNode *node, int num)
{
struct ListNode* ret = (struct ListNode* )calloc(1, sizeof(struct ListNode));
struct ListNode* result = ret;
for (int i = 0; i < num - 1; i++) {
ret->next = (struct ListNode* )calloc(1, sizeof(struct ListNode));
ret = ret->next;
}
ret->next = node;
return result;
}
int calculate(struct ListNode** result, struct ListNode* num1, struct ListNode* num2)
{
if (!num1 || !num2) {
return 0;
} else {
int num = calculate(result, num1->next, num2->next);
int sum = num1->val + num2->val + num;
struct ListNode *tmp = (struct ListNode* )calloc(1, sizeof(struct ListNode));
tmp->val = sum % 10;
//printf("val:%d\n", tmp->val);
tmp->next = *result;
*result = tmp;
return sum / 10;
}
}
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
if (!l1 && !l2) {
return NULL;
}
int len1 = getlength(l1);
int len2 = getlength(l2);
if (len1 > len2) {
l2 = extendList(l2, len1 - len2);
} else if( len2 > len1) {
l1 = extendList(l1, len2 - len1);
}
int len = len1 > len2 ? len1 : len2;
struct ListNode* ret = NULL;
int value = calculate(&ret, l1, l2);
if(value) {
struct ListNode *tmp = (struct ListNode* )calloc(1, sizeof(struct ListNode));
tmp->val = value;
tmp->next = ret;
ret = tmp;
}
return ret;
}
leetcode 445 lension learn:
1、 打印debug 时会导致链表头指针偏离, 打印debug正确后需要删除该部分,才能获取正确结果。 代码编写拷贝时出现入参 或者错别字的地基错误, 需要格外注意负责浪费过多的时间。
2、相加运算时需要记录进位信息, 且最高位的进位信息需要单独处理
3、 迭代运用的不够熟练, 特别是迭代函数中链表新元素创建之后需要赋值的过程。含义为创建新的节点后,原来的链表首节点作为新建节点的next, 再把新建节点作为返回链表result 的首节点。
struct ListNode *tmp = (struct ListNode* )calloc(1, sizeof(struct ListNode));
tmp->val = sum % 10;
//printf("val:%d\n", tmp->val);
tmp->next = *result;
*result = tmp;
return sum / 10;
1333

被折叠的 条评论
为什么被折叠?



