My16ms C solution, easy to understand


  • 0
    L
    struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    struct ListNode *head1 = l1;
    struct ListNode *head2 = l2;
    struct ListNode *result = (struct ListNode *)malloc(sizeof(struct ListNode));
    struct ListNode *p1, *p2;
    int buff = 0, dev = 0;
    
    if(head1 == NULL && head2 == NULL)
    {
        return NULL;
    }
    
    if(head1 == NULL)
    {
        return l2;
    }
    
    if(head2 == NULL)
    {
        return l1;
    }
    
    p1 = result;
    p1->next = NULL;
    while(head1 != NULL || head2 != NULL)
    {
        if(head1 != NULL && head2 == NULL)
        {
            buff = head1->val + dev;
    
            p2 = (struct ListNode *)malloc(sizeof(struct ListNode));
            p2->next = NULL;
            p1->next = p2;
            p2->val = buff % 10;
            head1 = head1->next;
            p1 = p1->next;
            dev = buff / 10;
        }
        else if(head1 == NULL && head2 != NULL)
        {
            buff = head2->val + dev;
    
            p2 = (struct ListNode *)malloc(sizeof(struct ListNode));
            p2->next = NULL;
            p1->next = p2;
            p2->val = buff % 10;
            head2 = head2->next;
            p1 = p1->next;
            dev = buff / 10;
        }
        else
        {
            buff = head1->val + head2->val + dev;
    
            p2 = (struct ListNode *)malloc(sizeof(struct ListNode));
            p2->next = NULL;
            p1->next = p2;
            p2->val = buff % 10;
            head1 = head1->next;
            head2 = head2->next;
            p1 = p1->next;
            dev = buff / 10;
        }
    }
    
    if(dev)
    {
        p2 = (struct ListNode *)malloc(sizeof(struct ListNode));
        p2->next = NULL;
        p1->next = p2;
        p2->val = dev;
    }
    result = result->next;
    return result;
    

    }


  • 0
    S

    I 've learn a lot from your code, thanks a lot. But the first lines is unnecessary. such as

    if(head1 == NULL && head2 == NULL)
    {
        return NULL;
    }
    
    if(head1 == NULL)
    {
        return l2;
    }
    
    if(head2 == NULL)
    {
        return l1;
    }

  • 0
    M

    you may mistake “L1” for "11" he just exclude some special case.


Log in to reply
 

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