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

add two interviewbit

The document contains a C++ implementation of a function to add two numbers represented as linked lists. It includes functions to reverse a linked list, add the values of two linked lists, and print the resulting linked list. The main function, addTwoNumbers, combines these functionalities to output the sum of the two input linked lists after reversing them.

Uploaded by

223117109135
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)
5 views

add two interviewbit

The document contains a C++ implementation of a function to add two numbers represented as linked lists. It includes functions to reverse a linked list, add the values of two linked lists, and print the resulting linked list. The main function, addTwoNumbers, combines these functionalities to output the sum of the two input linked lists after reversing them.

Uploaded by

223117109135
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/ 1

ListNode *reverse(ListNode *A)

{
if(A==NULL||A->next == NULL)
{
return A;
}
ListNode *t = reverse(A->next);
A->next->next = A;
A->next = NULL;
return t;
}
ListNode *addall(ListNode *A,ListNode *B)
{
ListNode *res = NULL;
ListNode *temp,*prev=NULL;
int c=0,sum;
while(A!=NULL||B!=NULL)
{
sum = c+(A?A->val:0)+(B?B->val:0);
c = (sum>=10)?1:0;
sum = sum%10;
temp = new ListNode(sum);
if(res == NULL)
{
res = temp;
}
else
{
prev->next = temp;
}
prev = temp;
if(A)
{
A=A->next;
}
if(B)
{
B=B->next;
}
}
if(c>0)
temp->next = new ListNode(c);
return res;
}
void print(ListNode*h)
{
while(h!=NULL)
{
cout<<h->val<<" ";
h = h->next;
}
cout<<"\n";
}
ListNode* Solution::addTwoNumbers(ListNode* A, ListNode* B) {
print(reverse(addall(reverse(A),reverse(B))));
}

You might also like