Question:
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Solution:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* NodeList *next;
* NodeList(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *addTwoNumbers(ListNode *head1, ListNode *head2) {
int n1=,n2=;
ListNode *ptr1=head1,*ptr2=head2;
while(ptr1!=NULL)
{
n1++;
ptr1=ptr1->next;
}
while(ptr2!=NULL)
{
n2++;
ptr2=ptr2->next;
}
vector<int> sum;
int temp;
ListNode *head_long,*head_short;
if(n1>=n2)
{
head_long=head1;
head_short=head2;
}
else
{
head_long=head2;
head_short=head1;
}
/////
ListNode *pt1=head_long,*pt2=head_short;
while(pt2!=NULL)
{
temp=pt1->val+pt2->val;
if(temp>=)
{
sum.push_back(temp%);
if(pt1->next==NULL)
{
sum.push_back();
}
else
pt1->next->val+=;
}
else
sum.push_back(temp);
pt1=pt1->next;pt2=pt2->next;
}
while(pt1!=NULL)
{
temp=pt1->val;
if(temp>=)
{
sum.push_back(temp%);
if(pt1->next==NULL)
{
sum.push_back();
}
else
pt1->next->val+=;
}
else
sum.push_back(temp);
pt1=pt1->next;
}
ListNode *result=new ListNode();
ListNode *rp=new ListNode();
rp=result;
ListNode *rq; for(vector<int>::iterator iter=sum.begin();iter!=sum.end();iter++)
{
rq=new ListNode();
rq->val=*iter;
rp->next=rq;
rp=rq;
} rp->next=NULL;
result=result->next;
return result;
}
};