-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadd_two_numbers_in_LL_2.cpp
More file actions
46 lines (44 loc) · 962 Bytes
/
Copy pathadd_two_numbers_in_LL_2.cpp
File metadata and controls
46 lines (44 loc) · 962 Bytes
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
#include <iostream>
using namespace std;
// Definition of linked list:
class Node {
public:
int data;
Node *next;
Node() {
this->data = 0;
this->next = NULL;
}
Node(int data) {
this->data = data;
this->next = NULL;
}
Node (int data, Node *next) {
this->data = data;
this->next = next;
}
};
Node *addTwoNumbers(Node *num1, Node *num2)
{
Node *dummy = new Node();
Node *curr = dummy;
Node *t1 = num1;
Node *t2 = num2;
int carry = 0;
while(t1 != NULL || t2 != NULL){
int sum = carry;
if(t1) sum += t1->data;
if(t2) sum += t2->data;
Node *nnode = new Node(sum % 10);
carry = sum / 10;
curr->next = nnode;
curr = curr->next;
if(t1) t1 = t1->next;
if(t2) t2 = t2->next;
}
if(carry){
Node *nnode = new Node(carry);
curr->next = nnode;
}
return dummy->next;
}