20 ms Solution in C


  • 0
    S

    struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {

    if(l1==NULL && l2==NULL)
        return NULL;
        
    if(l1==NULL && l2!=NULL) 
        return l2;
        
     if(l2==NULL && l1!=NULL) 
        return l1;      
    
        int carry=0;
        struct ListNode* res = NULL;
        struct ListNode* head = NULL;
        struct ListNode* prev=NULL;
        
        while (l1 && l2){
            
            if(prev==NULL)
                head=res=(struct ListNode*)malloc(sizeof(struct ListNode));
            else{
                res=(struct ListNode*)malloc(sizeof(struct ListNode));
                prev->next=res;
                
            }
                
    
            res->val=(l1->val+l2->val+carry)%10;
            carry = (l1->val+l2->val+carry)/10;
            
            res->next=NULL;
            
            l1=l1->next;
            l2=l2->next;
            
            prev=res;
            
        }
    
        while (l1){
            res=(struct ListNode*)malloc(sizeof(struct ListNode));
            prev->next=res;
            
            res->val=(l1->val+carry)%10;
            carry = (l1->val+carry)/10;
            
            res->next=NULL;
            
            l1=l1->next;
            prev=res;
        }
    
        while (l2){
    
            res=(struct ListNode*)malloc(sizeof(struct ListNode));
            prev->next=res;
            
            res->val=(l2->val+carry)%10;
            carry = (l2->val+carry)/10;
            
            res->next=NULL;
            
            l2=l2->next;
            prev=res;
        }
         
        if (carry>0){
            
            res=(struct ListNode*)malloc(sizeof(struct ListNode));
            res->val=carry;
            res->next=NULL;
            
            prev->next=res;
        }
         
        return head;
    }

Log in to reply
 

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