I got a node like this
struct ListNode {
int val;
ListNode *next;
ListNode()
: val(0), next(nullptr) {}
ListNode(int x)
: val(x), next(nullptr) {}
ListNode(int x, ListNode *next)
: val(x), next(next) {}
};
And I want to sum two link list using recursive I am not sure but I guess it is tail recursive
Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2, int carry = 0,ListNode *result = nullptr) {
int n1 = l1 != nullptr ? l1->val : 0;
int n2 = l2 != nullptr ? l2->val : 0;
int val = (n1 + n2 + carry) % 10;
if(result == nullptr){
result = new ListNode(val);
}else{
result->next = new ListNode(val);
result = result->next;
}
result = addTwoNumbers(l1->next != nullptr ? l1->next : nullptr,
l2->next != nullptr ? l2->next : nullptr,
(n1 + n2 + carry) - 10,result);
return result;
}
But I am getting an run time error. I can not see what is wrong,It should be work
Thank for your all answers.
Aucun commentaire:
Enregistrer un commentaire