-
Notifications
You must be signed in to change notification settings - Fork 0
/
2.txt
24 lines (21 loc) · 768 Bytes
/
2.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Add Two Numbers
Given two linked lists we have to generate a single linked list which is the sum of both the linked lists
We can create a dummy linked list and add both numbers from the both of the linked lists and stores that in dummy linked list.
Use a carry to store if there is carry or not.
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *res=new ListNode(0,NULL);
ListNode *temp=res;
int carry=0,sum=0;
while(l1 || l2){
sum=(l1==NULL?0:l1->val) + (l2==NULL?0:l2->val) + carry;
temp->next=new ListNode(sum%10);
carry=sum/10;
temp=temp->next;
l1=l1?l1->next:NULL;
l2=l2?l2->next:NULL;
}
if(carry){
temp->next=new ListNode(carry,NULL);
}
return res->next;
}