题解一:
迭代:首先判断整数0,然后分别遍历两段链表,将对应位数的值相加并存入新链表,再遍历新链表,将节点值val>=10的减10,并且其下一节点值val+=1。需要注意最后一位节点进位是将下一位节点值设置为1。
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if (l1.val == 0 && l1.next == null) return l2;//判断0
else if (l2.val == 0 && l2.next == null) return l1;
ListNode result = new ListNode();
ListNode temp = result;//相加
while (l1 != null && l2 != null) {
temp.next = new ListNode();
temp.next.val = (l1.val + l2.val);
l1 = l1.next;
l2 = l2.next;
temp = temp.next;
}
while (l1 != null) {
temp.next = new ListNode();
temp.next.val = l1.val;
l1 = l1.next;
temp = temp.next;
}
while (l2 != null) {
temp.next = new ListNode();
temp.next.val = l2.val;
l2 = l2.next;
temp = temp.next;
}
temp = result.next;//进位
while (temp != null) {
if (temp.val >= 10) {
temp.val -= 10;
if (temp.next != null) {
temp.next.val++;
} else {
temp.next = new ListNode();
temp.next.val = 1;
temp.next.next = null;
break;
}
}
temp = temp.next;
}
return result.next;
}
}