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
class Solution {
public:
int getListLength(ListNode* list)
{
int lenList=0;
ListNode* ptrNode=list;
while(ptrNode)
{
lenList++;
ptrNode=ptrNode->next;
}
return lenList;
}
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2)
{
if(!l1)
return l2;
if(!l2)
return l1;
ListNode* ptrLongList;
ListNode* ptrShortList;
if(getListLength(l1)>=getListLength(l2))
{
ptrLongList=l1;
ptrShortList=l2;
}
else
{
ptrShortList=l1;
ptrLongList=l2;
}
ListNode* ptrLNode=ptrLongList;
ListNode* ptrSNode=ptrShortList;
int nIncre=0;
int nSum=0;
while(ptrSNode->next)
{
nSum=ptrLNode->val+ptrSNode->val+nIncre;
nIncre = nSum>=10? 1:0;
ptrLNode->val=nSum%10;
ptrLNode=ptrLNode->next;
ptrSNode=ptrSNode->next;
}
nSum=ptrLNode->val+ptrSNode->val+nIncre;
nIncre = nSum>=10? 1:0;
ptrLNode->val=nSum%10;
while(ptrLNode->next)
{
ptrLNode=ptrLNode->next;
nSum=ptrLNode->val+nIncre;
nIncre = nSum>=10? 1:0;
ptrLNode->val=nSum%10;
}
if(nIncre==1)
{
ptrLNode->next=new ListNode(1);
}
return ptrLongList;
}
};