[c++] Second order pointer solution. 25ms.


  • 0
    Y

    The first 3 lines are crucial for benchmark, which is used in ranajeet's solution.

    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        if (!l1 and !l2) return NULL;
        if (!l1) return l2;
        if (!l2) return l1;
        
        ListNode *p1, *p2, **pp3;
        p1 = l1;
        p2 = l2;
        
        ListNode *l3;
        pp3 = &l3;
        
        int inc(0);
        while (p1 != NULL && p2 != NULL)
        {
            int s = p1->val + p2->val + inc;
            inc = s >= 10;
            s = s % 10;
            
            *pp3 = new ListNode(s);
            pp3 = &(*pp3)->next;
            
            p1 = p1->next;
            p2 = p2->next;
        }
        
        if (p1 != NULL)
        {
            p2 = p1;
        }
        
        while (p2 != NULL)
        {
            int s = p2->val + inc;
            inc = s >= 10;
            s = s % 10;
            
            *pp3 = new ListNode(s);
            pp3 = &(*pp3)->next;
            
            p2 = p2->next;
        }
        
        if (inc)
        {
            *pp3 = new ListNode(1);
        }
        
        return l3;
    }

Log in to reply
 

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