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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode * result= NULL;
ListNode * p1=l1,*p2=l2;
ListNode * pNew = NULL, * last = NULL;
int pro =0;
int val1=0 ,val2=0;
while(p1 || p2)
{
if(p1)
{
val1 =p1->val;
}else val1 =0;
if(p2)
{
val2 =p2->val;
}else val2 =0;
pNew =new ListNode(0);
pNew->val = val1 + val2 + pro;
if( 9 < pNew->val )
{
pNew->val -=10;
pro=1;
}else
pro=0;
if(!result)
{
result = pNew;
last = pNew;
}
else
{
last->next = pNew;
last = pNew;
}
if(p1) p1 = p1->next;
if(p2) p2= p2->next;
}
if(pro > 0)
{
pNew =new ListNode(pro);
last->next = pNew;
}
return result;
}
};