20ms C solution


  • 0
    R
    struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) 
    {
        int flag = 0;//carry bit flag
        int sum = 0;
        struct ListNode* result = (struct ListNode *)malloc(sizeof(struct ListNode));
        if(result)
        {
        	result -> val = 0;
    	    result -> next = NULL;
        }
        else
        {
        	return NULL;
        }
        struct ListNode* resultHead = result;
        while(l1 || l2 || flag)
        {	
    		//judge the carry bit
    		sum = (l1? (*l1).val : 0) + (l2? (*l2).val : 0) + flag;
    		flag = sum / 10;
    		sum %= 10;
    		
    		if(l1) l1 = l1 -> next;
    		if(l2) l2 = l2 -> next;
    		
    		
    		(*result).next = (struct ListNode *)malloc(sizeof(struct ListNode));
    		if(result -> next)
    		{
    			result = result -> next;
    			result -> val = sum;
    	    	result -> next = NULL;	
    		}
        }
        result = resultHead -> next;
        /*
        for(result = resultHead; result; result = tmp)
        {
                tmp = (*result).next;
                free(result);
        }
        */
       	return result;
    }

Log in to reply
 

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