My 16ms c soulution


  • 3
    T
    int calc(int a, int b,int *carry) {
        int sum = a + b + *carry;
        *carry = sum/10;
        return sum%10;
    }
    struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
        if(l1 == NULL) return l2;
        if(l2 == NULL) return l1;
        int carry = 0;
        struct ListNode* head = l1;
        l1->val = calc(l1->val, l2->val, &carry);
        struct ListNode* prv = l1;
        l1=l1->next;
        l2=l2->next;
        while(l1 || l2){
            
            int val1 = 0, val2 = 0;
            if(l1){
                val1 = l1->val;
            } else {
                prv->next = l2;
                goto end;
            }
            if(l2){
                val2 = l2->val;
            } else {
                goto end;
            }
            l1 = l1->next;
            l2 = l2->next;
            
            prv->next->val = calc(val1, val2, &carry);
            prv = prv->next;
        }
        end:
        while(carry){
            if(prv->next){
                prv->next->val = calc(0, prv->next->val, &carry);
                prv = prv->next;
            }else {
                prv->next = malloc(sizeof(struct ListNode));
                prv->next->val = calc(0, 0, &carry);
                prv->next->next = NULL;
            }
        }
        
        return head;
    }
    

    It will only alloc once the most~
    I had tried my best, but I know there are better solutions. If anyone coule tell me:)


Log in to reply
 

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