My C++ solution


  • 1
    D
    class Solution {
    public:
        ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
            ListNode* sum;
            sum = new ListNode(l1->val + l2->val);
            ListNode* p = sum;
            l1 = l1->next;
            l2 = l2->next;
            while(l1 != NULL || l2 != NULL || p->val > 9)
            {
                p->next = new ListNode(p->val / 10);
                p->val %= 10;
                p = p->next;
    
    
                if(l1)
                {
                    p->val += l1->val;
                    l1 = l1->next;
                }
    
                if(l2)
                {
                    p->val += l2->val;
                    l2 = l2->next;
                }
            }
            
            return sum;
        }
    };

Log in to reply
 

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