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

 

 1 /**
 2 * Definition for singly-linked list.
 3 * struct ListNode {
 4 * int val;
 5 * ListNode *next;
 6 * ListNode(int x) : val(x), next(NULL) {}
 7 * };
 8 */
 9 class Solution {
10 public:
11 ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
12 ListNode *root=new ListNode(0);
13 ListNode *curNode,*pNode;
14 curNode=root;
15 int i,j,sum=0,carry=0;
16 while(l1!=NULL||l2!=NULL)
17 {
18 if(l1==NULL)
19 i=0;
20 else
21 i=l1->val;
22 if(l2==NULL)
23 j=0;
24 else
25 j=l2->val;
26 sum=i+j+carry;
27 carry=sum/10;
28 sum%=10;
29 ListNode *pNode=new ListNode(sum);
30 curNode->next=pNode;
31 curNode=pNode;
32 
33 if(l1) l1 = l1->next;
34 if(l2) l2 = l2->next;
35 }
36 if(carry>0) 
37 { 
38 ListNode *pNode=new ListNode(1);
39 curNode->next = pNode;
40 }
41 
42 return root->next;
43 }
44 };