c solution - 19ms


  • 0
    G

    '''
    int getListLen(struct ListNode* listhead){
    int len = 0;
    struct ListNode* listptr = listhead;
    if(listptr == NULL){
    return len;
    }
    while(listptr){
    ++len;
    listptr = listptr->next;
    }
    return len;
    }

    struct ListNode* add(struct ListNode* l1, struct ListNode* l2){
    int overflow = 0;

    struct ListNode* l1ptr = l1;
    struct ListNode* l2ptr = l2;
    
    struct ListNode* resulthead = NULL;
    struct ListNode* resultptr = NULL;
    
    while(l1ptr){
        if(l2ptr){
            if(resulthead == NULL){
                resulthead = (struct ListNode*)malloc(sizeof(struct ListNode));
                resulthead->val = l1ptr->val + l2ptr->val;
                resulthead->next = NULL;
                if(resulthead->val > 9){
                    resulthead->val %= 10;
                    overflow = 1;
                }
                resultptr = resulthead;
                l1ptr = l1ptr->next;
                l2ptr = l2ptr->next;
            }
            else{
                resultptr->next = (struct ListNode*)malloc(sizeof(struct ListNode));
                resultptr = resultptr->next;
                resultptr->val = l1ptr->val + l2ptr->val + overflow;
                resultptr->next = NULL;
                if(resultptr->val > 9){
                    resultptr->val %= 10;
                    overflow = 1;
                }
                else{
                    overflow = 0;
                }
                l1ptr = l1ptr->next;
                l2ptr = l2ptr->next;
            }
        }
        else{
            resultptr->next = (struct ListNode*)malloc(sizeof(struct ListNode));
            resultptr = resultptr->next;
            resultptr->val = l1ptr->val + overflow;
            resultptr->next = NULL;
            if(resultptr->val > 9){
                resultptr->val %= 10; 
                overflow = 1;
            }
            else{
                overflow = 0;
            }
            l1ptr = l1ptr->next;
        }
    }
    if(overflow){
        resultptr->next = (struct ListNode*)malloc(sizeof(struct ListNode));
        resultptr = resultptr->next;
        resultptr->val = overflow;
        resultptr->next = NULL;
        overflow = 0;
    }
    return resulthead;
    

    }

    struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    int len1 = getListLen(l1);
    int len2 = getListLen(l2);

    struct ListNode* resulthead = NULL;
    
    if(len1 == 0){
        return l2;
    }
    if(len2 == 0){
        return l1;
    }
    
    if(len1 >= len2){
        resulthead = add(l1, l2);
    }
    else{
        resulthead = add(l2, l1);
    }
    
    return resulthead;
    

    }
    '''


Log in to reply
 

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