-
Notifications
You must be signed in to change notification settings - Fork 1
/
0002-add-two-numbers.c
89 lines (83 loc) · 2.14 KB
/
0002-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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
unsigned int len = sizeof(struct ListNode);
struct ListNode* head = NULL;
struct ListNode* temp = NULL;
int tempValue = 0;
int flag = 0;
if(NULL == l1->next||NULL == l2->next)
{
head = (struct ListNode*)malloc(len);
memset(head,0,len);
head->val = (l1->val + l2->val)%10;
flag = (l1->val + l2->val)/10;
temp = head;
l1 = l1->next;
l2 = l2->next;
}
else
{
while(NULL != l1&& NULL != l2)
{
tempValue = l2->val+l1->val;
struct ListNode* node = (struct ListNode*)malloc(len);
memset(node,0,len);
node->next = NULL;
node->val = (tempValue+flag)%10;
if(NULL == head)
{
head = node;
temp = head;
}
{
temp->next = node;
temp = temp->next;
}
flag = (tempValue+flag)/10;
l1 = l1->next;
l2 = l2->next;
}
}
if(NULL != l1)
{
while(NULL != l1)
{
struct ListNode* node = (struct ListNode*)malloc(len);
memset(node,0,len);
node->next = NULL;
node->val = (l1->val+flag)%10;
temp->next = node;
temp = temp->next;
flag = (l1->val+flag)/10;
l1=l1->next;
}
}
else if(NULL != l2)
{
while(NULL != l2)
{
struct ListNode* node = (struct ListNode*)malloc(len);
memset(node,0,len);
node->next = NULL;
node->val = (l2->val+flag)%10;
temp->next = node;
temp = temp->next;
flag =(l2->val+flag)/10;
l2=l2->next;
}
}
else{}
if(flag != 0)
{
temp->next = (struct ListNode*)malloc(len);
memset(temp->next,0,len);
temp->next->val = flag;
}
return head;
}