-
-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
2.c
57 lines (48 loc) · 1014 Bytes
/
2.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
/*
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode *addTwoNumbers(struct ListNode *l1, struct ListNode *l2)
{
struct ListNode *head = NULL;
struct ListNode *walk = NULL;
struct ListNode *tmp = NULL;
int carry = 0;
int val1 = 0;
int val2 = 0;
int val = 0;
while (l1 != NULL || l2 != NULL || carry)
{
val1 = 0;
val2 = 0;
val = 0;
if (l1)
{
val1 = l1->val;
l1 = l1->next;
}
if (l2)
{
val2 = l2->val;
l2 = l2->next;
}
val = carry + val1 + val2;
carry = val / 10;
tmp = malloc(sizeof(struct ListNode));
tmp->val = val % 10;
tmp->next = NULL;
if (!head)
{
head = walk = tmp;
}
else
{
walk->next = tmp;
walk = walk->next;
}
}
return head;
}