-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaddTwoNumbers.c
More file actions
37 lines (34 loc) · 778 Bytes
/
addTwoNumbers.c
File metadata and controls
37 lines (34 loc) · 778 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*
*/
#include <math.h>
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
int sum = 0;
struct ListNode *head = NULL, *tail = NULL;
while (l1 || l2 || sum) {
if (l1) {
sum += l1->val;
l1 = l1->next;
}
if (l2) {
sum += l2->val;
l2 = l2->next;
}
struct ListNode *node = malloc(sizeof(struct ListNode));
node->val = sum % 10;
node->next = NULL;
sum /= 10;
if (!head) {
head = node;
} else {
tail->next = node;
}
tail = node;
}
return head;
}