【C语言刷LeetCode】2.两数相加

方法2

struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
    if(l1==NULL && l2==NULL) return NULL;
   
    struct ListNode*a=(struct ListNode*)malloc(sizeof(struct ListNode));
    a->next=NULL;
    struct ListNode* head=a;
    int carry=0;
    while(l1!=NULL || l2!=NULL){
      
        int x=(l1!=NULL)?l1->val:0;
        int y=(l2!=NULL)?l2->val:0;
        int sum=x+y+carry;
       
        carry=sum/10;
        a->next=(struct ListNode*)malloc(sizeof(struct ListNode));
        a=a->next;
        a->val=sum%10;
        a->next=NULL;
        if(l1!=NULL) l1=l1->next;
        if(l2!=NULL) l2=l2->next;
    }
    if(carry>0) {
        a->next=(struct ListNode*)malloc(sizeof(struct ListNode));
        a=a->next;
        a->val=carry;
       a->next=NULL;
    }
    return head->next;
}

你可能感兴趣的:(LeetCode题)