-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2.Add Two Number
87 lines (87 loc) · 2.13 KB
/
2.Add Two Number
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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
if(l1==NULL||l2==NULL)
return l1==NULL?l2:l1;
struct ListNode *temp_1,*temp_2,*head,*end;
head=(struct ListNode*)malloc(sizeof(struct ListNode));
end=head;
temp_1=l1;
temp_2=l2;
int i=0;
int carry=0;
while(!(temp_1==NULL||temp_2==NULL))
{
struct ListNode*node=(struct ListNode*)malloc(sizeof(struct ListNode));
i=temp_1->val+temp_2->val+carry;
carry=i/10;
end->val=i%10;
if(temp_1->next==NULL&&temp_2->next==NULL&&carry==1)
{
end->next=node;
end=node;
end->val=1;
end->next=NULL;
}
if(temp_1->next==NULL&&temp_2->next==NULL&&carry==0)
end->next=NULL;
else
{
end->next=node;
end=node;
}
temp_1=temp_1->next;
temp_2=temp_2->next;
}
while(temp_1!=NULL)
{
struct ListNode*node=(struct ListNode*)malloc(sizeof(struct ListNode));
i=temp_1->val+carry;
end->val=i%10;
carry=i/10;
if(temp_1->next==NULL&&carry==0)
end->next=NULL;
else if(temp_1->next==NULL&&carry==1)
{
end->next=node;
end=node;
end->val=1;
end->next=NULL;
}
else
{
end->next=node;
end=node;
}
temp_1=temp_1->next;
}
while(temp_2!=NULL)
{
struct ListNode*node=(struct ListNode*)malloc(sizeof(struct ListNode));
i=temp_2->val+carry;
end->val=i%10;
carry=i/10;
if(temp_2->next==NULL&&carry==0)
end->next=NULL;
else if(temp_2->next==NULL&&carry==1)
{
end->next=node;
end=node;
end->val=1;
end->next=NULL;
}
else
{
end->next=node;
end=node;
}
temp_2=temp_2->next;
}
end->next=NULL;
return head;
}