Simplest C++ in O(n) Time & O(1) space


#1

int size(ListNode* A){
int n=0;
ListNode* temp=A;
while(temp!=NULL){
temp=temp->next;
n++;
}
return n;
}
ListNode* Solution::addTwoNumbers(ListNode* A, ListNode* B) {
int la=size(A);
int lb=size(B);
ListNode* temp;
if(la<lb){
temp=A;
A=B;
B=temp;
}
ListNode* x=A;
ListNode* y=B;
int carry=0;
while(x!=NULL){
if(carry!=0){
x->val=(x->val)+carry;
carry=0;
}
if(y!=NULL)x->val=(x->val)+(y->val);
if(x->val>9){
carry=x->val/10;
x->val=(x->val)%10;
}
temp=x;
x=x->next;
if(y!=NULL)y=y->next;
}
if(carry!=0){
temp->next=new ListNode(carry);
}
return A;
}