CPP Solution in 25ms


  • 0
    U

    Revised couple of times. a little bit additional space used: a dummy link header, a carry forward integer. Time used: 25ms.

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
            ListNode* h = new ListNode(0);
            ListNode* p = h;
            int carry = 0;
            while (l1 != NULL || l2 != NULL) {
                p->next = new ListNode(0);
                p = p->next;
                
                if (l1 != NULL) carry += l1->val, l1 = l1->next;
                if (l2 != NULL) carry += l2->val, l2 = l2->next;
    
                p->val = carry % 10;
                carry /= 10;
            }
            if (carry > 0) p->next = new ListNode(carry);
            return h->next;
        }
    };
    

Log in to reply
 

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