C++, O(1) space and O(n) time complexity


#1
ListNode* Solution::addTwoNumbers(ListNode* A, ListNode* B) {
    if(!A) return B;
    if(!B) return A;
    ListNode *ans=A, *prev=A; // "ans" is final and "prev" to keep last node
    int x; // to store sum value
    x=(A->val+B->val)%10;
    int r=(A->val+B->val)/10; // r is carry value
    A->val=x;
    A=A->next; B=B->next; 
    
    while(A && B)
    {
        prev=A;
        x=(A->val+B->val +r)%10;
        r=(A->val+B->val +r)/10;
        A->val=x;
        A=A->next;
        B=B->next;
    }
    
    while(A)
    {
        prev=A;
        x=(r+A->val)%10;
        r=(r+A->val)/10;
        A->val=x;
        A=A->next;
        
    }
    while(B)
    {
        prev->next=B;
        x=(r+B->val)%10;
        r=(r+B->val)/10;
        B->val=x;
        B=B->next;
        prev=prev->next;
    }
    if(r>0) prev->next=new ListNode(r); // if curry value remains in end
    return ans;
}