LinkedList: Add Two Numbers - C++

Run main look till list1 and list2 both of them reaches end and carry of two digit some is zero. keep adding carry to the sum. 

#code - cpp - C++

```cpp []
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    int add(ListNode* l1, ListNode* l2, int& carry){
        int sum = carry;
        if(l1)
            sum += l1->val;
        if(l2) 
            sum += l2->val;
        
        carry = sum / 10;
        if (carry > 0)
            sum =  sum % 10;
        return sum;
    }
    
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        int carry = 0; 
        int sum = 0;
        ListNode* root = nullptr;

        while(l1 || l2 || carry > 0) {
            ListNode* nnode = new ListNode(add(l1, l2, carry));
            if ( root == nullptr) {
                root = nnode;
            }
            else {
                ListNode* cur =root;
                while(cur->next != nullptr)
                    cur = cur->next;
                cur->next = nnode;
            }
            if(l1)
                l1 =l1->next;
            if(l2)
                l2 =l2->next;
        }
        return root;
    }
};

Comments

Popular posts from this blog

Two Sum : of Array Element thats equal to target sume

From Zero to Production-Ready: Your Year-Long Journey to Mastering System Design