class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
if (l1 == NULL and l2 == NULL) return NULL;
else if (l1 == NULL) return l2;
else if (l2 == NULL) return l1;
int a = l1>val + l2>val;
ListNode *p = new ListNode(a % 10);
p>next = addTwoNumbers(l1>next,l2>next);
if (a >= 10) p>next = addTwoNumbers(p>next, new ListNode(1));
return p;
}
};
Recursive 8 line C++ solution


Share my solution using recursion. Comments are welcome.
The idea is simple: we have 4 subcases giving two nodes as input. 1. both nodes are null. 2. The first one is null. 3. The second node is null. 4. both are not null.class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { return helper(l1, l2, 0); } ListNode* helper(ListNode* a, ListNode* b, int c) { if (a == NULL & b == NULL) { return (c == 1) ? new ListNode(1) : NULL; } else if (a == NULL) { return helper(b, NULL, c); } else if (b == NULL) { a>next = helper(a>next, NULL, (a>val+c) / 10); } else { a>next = helper(a>next, b>next, (a>val+b>val+c)/10); } a>val = (b == NULL) ? (a>val+c) % 10 : (a>val+b>val+c) % 10; return a; } };