C/c++ code is always pretty


  • 0
    D
     ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode *head = NULL;
        ListNode **linkp = &head;
        int carry = 0;
        while(l1 != NULL || l2 != NULL){
            int sum = carry + (l1? l1->val : 0) + (l2? l2->val : 0);
            *linkp = new ListNode(sum % 10);
            carry = sum / 10;
            linkp = &(*linkp)->next;
            if(l1)l1 = l1->next;
            if(l2)l2 = l2->next;
        }
        if(carry){
            *linkp = new ListNode(carry);
            (*linkp)->next = NULL;
        }else{
            *linkp = NULL;
        }
        
        return head;
    }

Log in to reply
 

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