forked from Ma63d/leetcode-viewer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
add-two-numbers.c
66 lines (66 loc) · 1.6 KB
/
add-two-numbers.c
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
struct ListNode *result, *currentNode, *headNode;
headNode = NULL;
int flag = 0;
while(l1 != NULL && l2 !=NULL) {
currentNode = (struct ListNode *)malloc(sizeof(struct ListNode));
currentNode->next = NULL;
if(l1->val + l2->val + flag > 9) {
currentNode->val = l1->val + l2->val + flag - 10;
flag = 1;
} else {
currentNode->val = l1->val + l2->val + flag;
flag = 0;
}
if (headNode == NULL) {
headNode = currentNode;
} else {
result->next = currentNode;
}
result = currentNode;
l1 = l1->next;
l2 = l2->next;
}
while(l1 != NULL) {
currentNode = (struct ListNode *)malloc(sizeof(struct ListNode));
currentNode->next = NULL;
if(l1->val + flag > 9){
currentNode->val = l1->val + flag - 10;
flag = 1;
} else {
currentNode->val = l1->val + flag;
flag = 0;
}
result->next = currentNode;
result = currentNode;
l1 = l1->next;
}
while(l2 != NULL) {
currentNode = (struct ListNode *)malloc(sizeof(struct ListNode));
currentNode->next = NULL;
if(l2->val + flag > 9){
currentNode->val = l2->val + flag - 10;
flag = 1;
} else {
currentNode->val = l2->val + flag;
flag = 0;
}
result->next = currentNode;
result = currentNode;
l2 = l2->next;
}
if(flag != 0) {
currentNode = (struct ListNode *)malloc(sizeof(struct ListNode));
currentNode->next = NULL;
currentNode->val = flag;
result->next = currentNode;
}
return headNode;
}