Readable c++ elegant solution

programming
Tags: #<Tag:0x00007f2422e30fb0>

#1

ListNode* Solution::addTwoNumbers(ListNode* A, ListNode* B) {

ListNode* currentA=A;
ListNode* currentB=B;
ListNode* head;
ListNode* current;
int init = 1;
int carry = 0;

while (currentA != nullptr || currentB != nullptr || carry !=0)
{
    int sum = 0;
    int dig = 0;
    if(currentA != nullptr)
    {
       sum += currentA->val;
       currentA = currentA->next;
    }
    
      if(currentB != nullptr)
    {
       sum += currentB->val;
       currentB= currentB->next;
    }
    
    sum += carry; 
    carry = sum / 10;
    dig = sum % 10;
    
    if(init)
    {
      current = new ListNode(dig);        
      head = current; 
      init=0;
    }
    else
    {
        current->next = new ListNode(dig);
        current=current->next;
    }
}

return head;

}