问题描述
- leetcode 002 add two numbers C语言
-
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) { struct ListNode *l, *p; l = (struct ListNode*)malloc(sizeof(struct ListNode)); l->val = l1->val + l2->val; p = l; l1 = l1->next; l2 = l2->next; while(l1||l2||p->val>9) { p->next = (struct ListNode*)malloc(sizeof(struct ListNode)); p->next->val = p->val/10; p->val %= 10; p = p->next; if(l1) { p->val += l1->val; l1 = l1->next; } if(l2) { p->val += l2->val; l2 = l2->next; } } return l; }
请问这样有错吗?我自己反复看了觉得没有问题啊,原题 如下
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
解决方案
链表没有终结.每次malloc后马上给新生出的节点的next赋NULL值就可以了.移动两个地方。
l->next = NULL;
和
p->next->next = NULL;
时间: 2024-08-03 07:43:11