-
Notifications
You must be signed in to change notification settings - Fork 0
/
033_AddTwoNumbersAsLinkedLists.cpp
71 lines (58 loc) · 1.35 KB
/
033_AddTwoNumbersAsLinkedLists.cpp
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
/****************************************************************
Following is the class structure of the Node class:
class Node
{
public:
int data;
Node *next;
Node(int data)
{
this->data = data;
this->next = NULL;
}
};
*****************************************************************/
#include<bits/stdc++.h>
using namespace std;
class Node
{
public:
int data;
Node *next;
Node(int data)
{
this->data = data;
this->next = NULL;
}
};
Node *addTwoNumbers(Node *head1, Node *head2)
{
// Write your code here.
Node *l1=head1;
Node *l2=head2;
Node *dummy = new Node(0);
Node *l3=dummy;
int carry=0;
while(l1 || l2){
int num1=l1?l1->data:0;
int num2=l2?l2->data:0;
int sum=num1+num2+carry;
carry=sum/10;
sum=sum%10;
Node *n= new Node(sum);
l3->next=n;
l3=l3->next;
if(l1){
l1=l1->next;
}
if(l2){
l2=l2->next;
}
}
if(carry>0){
Node *n= new Node(carry);
l3->next=n;
l3=l3->next;
}
return dummy->next;
}