0% found this document useful (0 votes)
9 views

Leetcode

leetcode question

Uploaded by

iadityasingh13
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Leetcode

leetcode question

Uploaded by

iadityasingh13
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

Node*reverse(Node*head){

Node* curr= head;


Node* prev= Null;
Node* next= Null;
while(curr!= Null){
next= curr -> next;
curr -> next=prev;
curr = next;
}
return prev;
}

void insertAtTail(struct node* &head, struct Node* &tail, int val){


Node* temp= new Node(val);
if(head == Null){
head= temp;
tail= temp;
return= temp;
}
else{
tail -> next = temp;
tail= temp;
}
}

struct Node* add(struct Node* l1, struct Node* l2){


int carry= 0;
Node* ansHead= Null;
Node* ansTail= Null;
while(l1!= Null && l2!= Null){
int sum= carry+ l1 -> data + l2 -> data;
int digit= sum%10;
insertAtTail(ansHead, ansTail, digit);
carry= sum/10;
l1 = l1->Next;
l2 = l2->Next;
}
}

while(l1!= Null){
int sum=carry + l1->data;
int digit=sum%10;
insertAtTail(ansHead, ansTail, digit);
carry= sum/10;
l1=l1->Next;
}
while(l2!= Null){
int sum=carry + l2->data;
int digit=sum%10;
insertAtTail(ansHead, ansTail, digit);
carry= sum/10;
l2=l2->Next;
}
while(carry!= 0){
int sum=carry;
int digit=sum%10;
insertAtTail(ansHead, ansTail, digit);
carry= sum/10;
}
public:
struct Node* addTwolist(struct Node* l1, struct Node* l2){
l1= reverse(l1);
l2= reverse(l2);
Node* ans= add(l1 + l2);
ans= reverse(ans);
return ans;

You might also like