# C++ O(1) recursive solution

• For 2 lists below,
x1->x2->x3->x4
y1->y2
I want call it like (x1,null)->(x2,null)->(x3,y1)->(x4,y2).
To realize this ,I will get length of two lists first,then we call the recursive function with longer list's head and shorter lists' as NULL,when the remain length of longer list is equal to the shorer lists length.we change NULL to shorter list's pointer.

code is list below:

class Solution {

public:

``````ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
if(l1==NULL) return l2;
if(l2==NULL) return l1;
int nLen1 = 0,nLen2 = 0 ,nCarry = 0;
while(p){
p=p->next;
nLen1++;
}
p = l2;
while(p){
p = p->next;
nLen2++;
}
if(nLen1==nLen2){
}else if(nLen1>nLen2){
}else{
}
if(nCarry){
}
``````

private:

``````ListNode* addTwoNum(ListNode* l1, ListNode* l2,int nCnt,int& nCarry) {
int nSum;
if(l1==NULL) return NULL;
if(nCnt>0){

nSum = l1->val+nCarry;
nCarry = nSum/10;

}else{

nSum = l1->val+l2->val+nCarry;
nCarry = nSum/10;
}
}
``````

};

``````ListNode* head = NULL;
``````

};

• This post is deleted!

• This post is deleted!

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