這個(gè)題很像大數(shù)相加,一共有三個(gè)思路:
第一種:迭代寫法问窃。
考慮三種情況:
1.l1與l2都為null時(shí),返回進(jìn)位值泡躯。
2.l1與l2有一個(gè)為null時(shí),返回那個(gè)不為null的值
3.l1與l2都不為null時(shí)较剃,考慮鏈表長度不一樣,小的那個(gè)鏈表以0代替写穴。
代碼如下:java實(shí)現(xiàn):
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;
}
}