两个linkedlist相加,从低位到高位,很容易。
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
return helper(l1,l2,0);
}
public ListNode helper(ListNode l1, ListNode l2, int carry){
if (l1==null && l2==null && carry==0) return null;
if (l1!=null){
carry+=l1.val;
l1=l1.next;
}
if (l2!=null){
carry+=l2.val;
l2=l2.next;
}
ListNode current = new ListNode(carry%10);
current.next = helper(l1,l2,carry/10);
return current;
}
No comments:
Post a Comment