# My C++ solution (optimise the code more if you cant thanks)

this is my code here, and it works perfectly fine, but it is a long code so can anybody help in making my code much more smaller as few things are repeated in my code …

/**

• struct ListNode {

• ``````int val;
``````
• ``````ListNode *next;
``````
• ``````ListNode(int x) : val(x), next(NULL) {}
``````
• };
/
ListNode
ListNode *C= NULL , *tempc = C;
int sum= 0 , carry = 0;
ListNode *tempa = A , *tempb = B;
if(A==NULL) return B;
if(B==NULL) return A ;
while(tempa!=NULL && tempb!=NULL){
sum += carry + tempa->val + tempb->val ;
carry = sum/10 ;
sum = sum%10 ;
if(C== NULL){
C = new ListNode(sum);
tempc =C;
tempc->next = NULL;
} else {
tempc->next = new ListNode(sum);
tempc=tempc->next ;
tempc->next = NULL;
}
tempa = tempa->next;
tempb = tempb->next ;
sum= 0;
}

// cout << "Carry is --> " <<carry <<endl;

if(tempa == NULL){
if(carry == 0) tempc ->next = tempb ;
if(carry !=0){
sum =0 ;
while(tempb!=NULL){
sum += carry + tempb->val ;
carry = sum/10 ;
sum = sum%10 ;
tempc->next = new ListNode(sum);
tempc=tempc->next ;
tempc->next = NULL;
tempb = tempb->next ;
sum = 0;
}
}

} else if(tempb == NULL){
if(carry == 0) tempc ->next = tempa ;
if(carry !=0){
sum= 0;
while(tempa!=NULL){
sum += carry + tempa->val ;
carry = sum/10 ;
sum = sum%10 ;
tempc->next = new ListNode(sum);
tempc=tempc->next ;
tempc->next = NULL;
tempa = tempa->next ;
sum = 0;
}
}
}
return C ;

}