My acceptance C++ solution


  • 1
    S

    class Solution {
    public:
    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {

        int remain = 0;
        ListNode* head = new ListNode(0);
        ListNode* cur = head;
    
        while(l1 != NULL ||  l2 != NULL)
        {
            int val1 = 0, val2 = 0;
            if(l1 != NULL)
            {
                val1 = l1->val;
            }
    
            if(l2 != NULL)
            {
                val2 = l2->val;
            }
            
            int value = val1 + val2 + remain;
            remain = 0;
            if(value >= 10)
            {
                value -= 10;
                remain = 1;
            }
    
            ListNode * pos = new ListNode(value);
            cur->next = pos;
            cur = cur->next;
    
            if(l1 != NULL)
                l1 = l1->next;
    
            if(l2 != NULL)
                l2 = l2->next;
        }
    
        if(remain != 0)
        {
            ListNode* pos = new ListNode(remain);
            cur->next = pos;
        }
        return head->next;
    }
    

    };


Log in to reply
 

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