这个题很像大数相加,一共有三个思路:
第一种:迭代写法。
考虑三种情况:
1.l1与l2都为null时,返回进位值。
2.l1与l2有一个为null时,返回那个不为null的值
3.l1与l2都不为null时,考虑链表长度不一样,小的那个链表以0代替。
代码如下:java实现:
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = new ListNode(0);
if(l1==null && l2==null ){
return head;
}
int sum = 0; int carry = 0;
ListNode curr = head;
while(l1 != null || l2 != null){
int num1 = l1 == null? 0 :l1.val;
int num2 = l2 == null? 0 :l2.val;
sum = num1 + num2 + carry;
curr.next = new ListNode(sum%10);
curr = curr.next;
carry = sum /10;
l1 = l1 == null? null : l1.next;
l2 = l2 == null? null : l2.next;
}
if(carry != 0){
curr.next = new ListNode(carry);
}
return curr.next;
}
}
第二种:递归写法:
public class Solution {
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){
return carry == 0? null : new ListNode(carry);
}
if(l1==null && l2!=null){
l1 = new ListNode(0);
}
if(l2==null && l1!=null){
l2 = new ListNode(0);
}
int sum = l1.val + l2.val + carry;
ListNode curr = new ListNode(sum % 10);
curr.next = helper(l1.next, l2.next, sum / 10);
return curr;
}
}