Simple O(n) CPP solution


#1

ListNode* Solution::addTwoNumbers(ListNode* A, ListNode* B) {
if(!A) return B;
if(!B) return A;
ListNode *start = new ListNode(0);
ListNode *it = start;
ListNode *prev = NULL;
int c = 0;
while(A && B){
it->val = (A->val + B->val + c)%10;
c = (A->val + B->val+c)/10;
ListNode *temp = new ListNode(0);
prev = it;
it->next = temp;
it = it->next;
A = A->next;
B = B->next;
}
while(A){
it->val = (A->val + c)%10;
c = (A->val+c)/10;
ListNode *temp = new ListNode(0);
it->next = temp;
prev = it;
it = it->next;
A = A->next;
}
while(B){
it->val = (B->val + c)%10;
c = (B->val+c)/10;
ListNode *temp = new ListNode(0);
it->next = temp;
prev = it;
it = it->next;
B = B->next;
}
if© it->val = c;
else prev->next = NULL;
return start;
}