Simple solution C++ solution


  • 0
    A

    '''

     int length(ListNode*  head){
        if(head ==  nullptr) return 0;   
        int length = 0;
        while(head != nullptr){
            head = head->next;
            length++;
        }
        return length;
    }
    
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        if(!l2) return l1;
        if(!l1) return l2;
        int m = length(l1), n = length(l2), diff = abs(m - n), carry = 0;
        //If lists are of same length call helper function
        if(m == n) {
            ListNode* head = addTwoNumbersSameLength(l1, l2, &carry);
            if(carry == 1){
                ListNode* temp = new ListNode(1);
                temp->next = head;
                head = temp;
            }
            return head;
        }
        //Else iterate until we get two lists of same length
        ListNode* itr1 = m > n ? l1 : l2; // bigger list
        ListNode* itr2 = m < n ? l1 : l2; // smaller list
        stack<ListNode*> s;
        while(diff > 0){
            s.push(itr1);
            itr1 = itr1->next;
            diff--;
        }
        //Gives the resulting list from the addition of two lists of equal length
        ListNode* head = addTwoNumbersSameLength(itr1, itr2, &carry);
        
        //Stack is used to iterate over the remaining part of the list in reverse order
        while(!s.empty()){
            int n = s.top()->val + carry;
            carry = n/10;
            ListNode* temp = new ListNode(n % 10);
            temp ->next = head;
            head = temp;
            s.pop();
        }
        if(carry == 1){
                ListNode* temp = new ListNode(1);
                temp->next = head;
                return temp;
        }
        return head;
    }
    
    ListNode* addTwoNumbersSameLength(ListNode* l1, ListNode* l2, int* carry){
        if(l1 == nullptr) return nullptr;
        ListNode* temp = addTwoNumbersSameLength(l1->next, l2->next, carry);
        int n = (l1->val + l2->val + *carry) % 10;
        *carry = (l1->val + l2->val + *carry) / 10;
        ListNode* head = new ListNode(n);
        head->next = temp;
        return head;
    }
    

    '''


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.