2. Add Two Numbers
problem description
example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.algorithm thought
code
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2,int add=0) {
if(l1==NULL){
if(add==0)
return l2;
l1=new ListNode(add);
return addTwoNumbers(l1,l2,0);
}else if(l2==NULL){
if(add==0)
return l1;
l2=new ListNode(add);
return addTwoNumbers(l1,l2,0);
}//上面是递归基
ListNode* res=new ListNode((l1->val+l2->val+add)%10);
res->next=addTwoNumbers(l1->next,l2->next,(l1->val+l2->val+add)/10);
return res;
}
};algorthm analysis
Last updated