-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadd-two-numbers.c
More file actions
45 lines (37 loc) · 905 Bytes
/
add-two-numbers.c
File metadata and controls
45 lines (37 loc) · 905 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
38
39
40
41
42
43
44
45
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* create_node(int val){
struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
node->val = val;
node->next = NULL;
return node;
}
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
int carry = 0;
struct ListNode* head = NULL;
struct ListNode* tail;
while(l1 || l2 || carry){
if(l1){
carry += l1->val;
l1 = l1->next;
}
if(l2){
carry += l2->val;
l2 = l2->next;
}
if(head == NULL){
head = create_node(carry % 10);
tail = head;
}else{
tail->next = create_node(carry % 10);
tail = tail->next;
}
carry /= 10;
}
return head;
}