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
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
if (!l1) return l2;
if (!l2) return l1;
ListNode * l3 = new ListNode(0);
ListNode * p = l3;
int cur = 0;
ListNode *p1 = l1;
ListNode * p2 = l2;
while(p1 || p2 || cur)
{
cur += (p1 != nullptr ? p1->val : 0) +(p2 != nullptr ? p2->val : 0);
p->val = cur % 10;
cur /= 10;
if(p1)
p1 = p1->next;
if(p2)
p2 = p2->next;
if(p1 || p2 || cur)
{
p->next = new ListNode(0);
p = p->next;
}
}
return l3;
}