-
Notifications
You must be signed in to change notification settings - Fork 0
/
002_AddTwoNumbers.c
79 lines (66 loc) · 1.68 KB
/
002_AddTwoNumbers.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
67
68
69
70
71
72
73
74
75
76
77
78
79
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
int tmp = 0;
struct ListNode* retls = NULL;
retls = (struct ListNode*)malloc(sizeof(struct ListNode));
if(retls == NULL) {
printf("malloc failed!\n");
return retls;
}
retls->val = 0;
retls->next = NULL;
struct ListNode *curl1 = l1;
struct ListNode *curl2 = l2;
struct ListNode *curret = retls;
while((curl1 != NULL) && (curl2 != NULL)) {
tmp = curret->val + curl1->val + curl2->val;
curret->val = tmp % 10;
if((curl1->next == NULL) && (curl2->next == NULL) && (tmp < 10)) {
curret->next = NULL;
}
else {
// Adding an new item to the end of the retls.
curret->next = (struct ListNode*)malloc(sizeof(struct ListNode));
curret->next->val = tmp / 10;
curret->next->next = NULL;
curret = curret->next;
}
curl1 = curl1->next;
curl2 = curl2->next;
}
while(curl1 != NULL) {
tmp = curret->val + curl1->val;
curret->val = tmp % 10;
if((curl1->next == NULL) && (tmp < 10)) {
curret->next = NULL;
}
else {
curret->next = (struct ListNode*)malloc(sizeof(struct ListNode));
curret->next->val = tmp / 10;
curret->next->next = NULL;
curret = curret->next;
}
curl1 = curl1->next;
}
while(curl2 != NULL) {
tmp = curret->val + curl2->val;
curret->val = tmp % 10;
if((curl2->next == NULL) && (tmp < 10)) {
curret->next = NULL;
}
else {
curret->next = (struct ListNode*)malloc(sizeof(struct ListNode));
curret->next->val = tmp / 10;
curret->next->next = NULL;
curret = curret->next;
}
curl2 = curl2->next;
}
return retls;
}