-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleet2.cpp
More file actions
48 lines (48 loc) · 1.15 KB
/
Copy pathleet2.cpp
File metadata and controls
48 lines (48 loc) · 1.15 KB
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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* head = NULL ;
ListNode* cur = NULL ;
int ni = 0 ;
while(l1 != NULL && l2!= NULL){
int nv = l1->val+l2->val+ni ;
ni = nv/10 ;
nv = nv%10 ;
ListNode* t = new ListNode(nv) ;
if(head == NULL){
head = t ;
}else{
cur->next =t ;
}
cur = t ;
l1 = l1->next ;
l2 = l2->next ;
}
ListNode* cc = l1 ;
if(l1 == NULL)
cc = l2 ;
while(cc!=NULL){
int nv = cc->val + ni ;
ni = nv/10 ;
nv = nv%10 ;
ListNode *t = new ListNode(nv) ;
cur->next = t ;
cur = t ;
cc = cc->next ;
}
if(ni>0){
ListNode *t = new ListNode(ni) ;
cur->next =t ;
t = cur ;
}
return head ;
}
};