Cpp code run through correct in visual studio but get error with 0, 1 input


  • 0
    S
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
    
    int carry = 0;
    ListNode *svalue = new ListNode(0);
    ListNode *sum;
    sum = svalue;
    
    if (l1 != NULL || l2 != NULL) {
    	while (l1->next != NULL || l2->next != NULL) {
    		if (l1->next != NULL && l2->next != NULL) {
    			sum->next = new ListNode(0);
    			sum->val = (l1->val + l2->val + carry) % 10;
    			carry = (l1->val + l2->val + carry) / 10;
    			sum = sum->next;
    			sum->next = NULL;
    			l1 = l1->next;
    			l2 = l2->next;
    		}
    		else if (l1->next == NULL) {
    			sum->next = new ListNode(0);
    			sum->val = (l2->val + carry) % 10;
    			carry = (l2->val + carry) / 10;
    			sum = sum->next;
    			sum->next = NULL;
    			l2 = l2->next;
    		}
    		else {
    			sum->next = new ListNode(0);
    			sum->val = (l1->val + carry) % 10;
    			carry = (l1->val + carry) / 10;
    			sum = sum->next;
    			sum->next = NULL;
    			l1 = l1->next;
    		}
    	}
    }
    
    if (carry > 0) {
    	sum->next = new ListNode(0);
    	sum->val = carry;
    	sum = sum->next;
    	sum->next = NULL;
    }
    
    return svalue;
    

    }


Log in to reply
 

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