My C recursive solution


  • 0
    B

    My C solution can resolve most cases of customized cases, but by submitting the code, I got struct alignment error, is anybody know why?

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     struct ListNode *next;
     * };
     */
     struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2);
     struct ListNode* addTwoNumbersExt(int carry, struct ListNode* l1, struct ListNode* l2);
     struct ListNode* addNumbers(struct ListNode* l);
     bool checkHasNext(struct ListNode* l1, struct ListNode* l2, int carry);
     
     
     
    struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
      return addTwoNumbersExt(0, l1, l2); 
    }
    
    
    struct ListNode* addTwoNumbersExt(int carry, struct ListNode* l1, struct ListNode* l2) {
        struct ListNode* lnew = malloc(sizeof(struct ListNode));
        if(!l1 && !l2){
            if(carry > 0){
                lnew->val = carry;
            }    
            return lnew;
        }
    
        if(!l1){
            lnew->val = l2->val + carry;
            lnew->next = addNumbers(l2->next);
        }
        
        if(!l2){
            lnew->val = l1->val + carry;
            lnew->next = addNumbers(l1->next);
        }
    
        
        int tmp;
        tmp = l1->val + l2->val + carry;
        lnew->val = tmp%10;
        if(checkHasNext(l1, l2, tmp/10))
            lnew->next = addTwoNumbersExt(tmp/10,l1->next, l2->next);
            
        return lnew;
    }
    
    
    bool checkHasNext(struct ListNode* l1, struct ListNode* l2, int carry){
        return (l1->next || l2->next || carry!= 0);
    }
    
    struct ListNode* addNumbers(struct ListNode* l) {
        struct ListNode* lnew = malloc(sizeof(struct ListNode));    
        if(!l)
            return  lnew;
        
        lnew->val = l->val;
        lnew->next = addNumbers(l->next);
        return lnew;
    }
    
    

  • 0
    B

    The error is as the following:
    "member access within misaligned address 0x000000000ff1 for type 'struct ListNode', which requires 8 byte alignment "


Log in to reply
 

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