# leetcode 两数相加 II

eg:
l1 (2 -> 4 -> 3 -> 6)
l2 (5 -> 6 -> 4)
res (3 -> 0 -> 0 -> 0)

public ListNode addTwoNumbers2(ListNode l1, ListNode l2) {
// 取链表长度
int len1 = length(l1);
int len2 = length(l2);
// 判断特殊参数case
if (len1 == 0) return l2;
if (len2 == 0) return l1;
// 补0. 如示例   l2 (5 -> 6 -> 4) 补0后 (0->5->6->4)
if (len1 > len2) {
l2 = fillZero(l2, len1 - len2);
} else {
l1 = fillZero(l1, len2 - len1);
}
int len = Math.max(len1, len2);

ListNode temp1 = null;
int length = len;
// 逐个相加并反转结果链表. 反转是为了后续进位
// 如示例temp1循环后为 10->9->9->2
while (length-- > 0) {
ListNode node = new ListNode(l1.val + l2.val);
l1 = l1.next;
l2 = l2.next;
node.next = temp1;
temp1 = node;
}

ListNode temp2 = null;
int carry = 0;
// 处理大于10的节点进位并反转结果倒序变成顺序
// 10->9->9->2 => 3->0->0->0
while (len-- > 0) {
ListNode node = new ListNode((temp1.val + carry) % 10);
node.next = temp2;
temp2 = node;
carry = (temp1.val + carry) >= 10 ? 1 : 0;
temp1 = temp1.next;
}

// 处理最后还有进位的前面补1。
// 如temp2 = 8->8 + 2 -> 2 = 1->0, carry = 1。补1就是最终结果110
ListNode result = temp2;
if (carry == 1) {
ListNode node = new ListNode(1);
node.next = temp2;
result = node;
}
return result;
}

private ListNode fillZero(ListNode node, int i) {
while (i-- > 0) {
ListNode temp = new ListNode(0);
temp.next = node;
node = temp;
}
return node;
}

private int length(ListNode node) {
int length = 0;
while (node != null) {
length++;
node = node.next;
}
return length;
}

/**
class ListNode {
int val;
ListNode next;

ListNode(int x) {
val = x;
}
}
*/


©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客