耗时一小时,这道题一开始的思路和递归没有关系。这种题的边界条件非常耗时,对于不好处理的地方,应该要使用别的方法来代替处理才行。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode root = new ListNode();
ListNode temp = root;
ListNode last = temp;
int carry = 0;
while (l1 != null && l2 != null) {
int sum = l1.val + l2.val + carry;
if (sum < 10) {
temp.val = sum;
carry = 0;
} else {
int x = sum % 10;
temp.val = x;
carry = 1;
}
ListNode newNode = new ListNode(-1);
last = temp;
temp.next = newNode;
temp = temp.next;
l1 = l1.next;
l2 = l2.next;
}
// l1和l2总有一个是等于null的
// l1还没有结束,把l1的值加到root后面
if (l1 != null) {
while (l1 != null) {
int singleSum = l1.val + carry;
if (singleSum < 10) {
temp.val = singleSum;
carry = 0;
} else {
int x = singleSum % 10;
temp.val = x;
carry = 1;
}
ListNode newNode = new ListNode(-1);
last = temp;
temp.next = newNode;
temp = temp.next;
l1 = l1.next;
}
if (carry == 1) {
temp.val = carry;
}
} else {
if (carry == 1) {
temp.val = carry;
}
}
// l2还没有结束,把l2的值加到root后面
if (l2 != null) {
while (l2 != null) {
int singleSum = l2.val + carry;
if (singleSum < 10) {
temp.val = singleSum;
carry = 0;
} else {
int x = singleSum % 10;
temp.val = x;
carry = 1;
}
ListNode newNode = new ListNode(-1);
last = temp;
temp.next = newNode;
temp = temp.next;
l2 = l2.next;
}
if (carry == 1) {
temp.val = carry;
}
} else {
if (carry == 1) {
temp.val = carry;
}
}
if (temp.val == -1) {
last.next = null;
}
return root;
}
}