-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2. Add two Numbers O(1) Method
44 lines (40 loc) · 1.1 KB
/
2. Add two Numbers O(1) Method
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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
void insert(ListNode* &head,ListNode* &tail, int n){
ListNode* node= new ListNode(n);
if(head== NULL){
head= node;
tail= node;
return;
}
tail->next= node;
tail= node;
}
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int carry=0;
ListNode* head= NULL;
ListNode* tail= NULL;
while(l1!=NULL || l2!=NULL || carry!=0 ){
int val1= 0;
if(l1!=NULL) val1= l1->val;
int val2=0;
if(l2!=NULL) val2= l2->val;
int sum= carry+ val1+val2;
carry= sum/10;
insert(head, tail, sum%10);
if(l1!=NULL) l1= l1->next;
if(l2!=NULL) l2= l2->next;
}
return head;
}
};