-
Notifications
You must be signed in to change notification settings - Fork 0
/
034_AddTwoNumbersAsLinkedListsll.cpp
74 lines (57 loc) · 1.43 KB
/
034_AddTwoNumbersAsLinkedListsll.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
72
73
74
#include<bits/stdc++.h>
using namespace std;
/************************************************************
Following is the linked list node structure:
************************************************************/
template <typename T>
class Node {
public:
T data;
Node* next;
Node(T data) {
next = NULL;
this->data = data;
}
};
Node<int>* reverseLL(Node<int>* head){
Node<int>* curr=head;
Node<int>* prev=NULL;
while(head){
curr=head;
head=head->next;
curr->next=prev;
prev=curr;
}
head=curr;
return head;
}
Node<int>* addTwoLists(Node<int>* first, Node<int>* second) {
// Write your code here.
first=reverseLL(first);
second=reverseLL(second);
Node<int>* dummy=new Node<int>(0);
Node<int>* head=dummy;
int carry=0;
while(first || second){
int num1=first?first->data:0;
int num2=second?second->data:0;
int sum=num1+num2+carry;
carry=sum/10;
sum%=10;
Node<int>* newNode= new Node<int>(sum);
head->next=newNode;
head=head->next;
if(first){
first=first->next;
}
if(second){
second=second->next;
}
}
if(carry){
Node<int>* newNode= new Node<int>(carry);
head->next=newNode;
head=head->next;
}
return reverseLL(dummy->next);;
}