LeeCode 两数相加(Java)(递归)
JAVA 代码
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
// 判断各个连表为0的情况
if (l1.val == 0 && l1.next == null){
return l2;
}
if (l2.val == 0 && l2.next == null){
return l1;
}
// 开始递归
return doAdd(l1, l2, 0);
}
/**
* 执行累加操作
*
*
* @param l1 连表1
* @param l2 连表2
* @param carry 进位标识
* @return
*/
public ListNode doAdd(ListNode l1, ListNode l2, int carry) {
int val = l1.val + l2.val + carry;
if (val>=10){
carry =1;
val -= 10;
}else {
carry = 0;
}
l1.val = val;
if (l1.next != null){
// 从判断连表1有无下一个 有的话执行递归并将返回值赋给上次递归的next
ListNode listNode = l2.next == null ? new ListNode(0) : l2.next;
l1.next = doAdd(l1.next,listNode,carry);
}else if (l2.next != null){
// 如果连表l1没有下一个了 就去判断连表2有无下一个 并将返回值赋给连表1的next
l1.next = doAdd(new ListNode(0),l2.next,carry);
}
// 判断进位标记 在链表末尾进位
if (carry>0 && l1.next == null){
l1.next = new ListNode(1);
}
// 返回l1
return l1;
}
}