给定两个 非空链表 l1
和 l2
来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。
可以假设除了数字 0 之外,这两个数字都不会以零开头。
示例1:
输入:l1 = [7,2,4,3], l2 = [5,6,4]
输出:[7,8,0,7]
示例2:
输入:l1 = [2,4,3], l2 = [5,6,4]
输出:[8,0,7]
示例3:
输入:l1 = [0], l2 = [0]
输出:[0]
提示:
- 链表的长度范围为
[1, 100]
0 <= node.val <= 9
- 输入数据保证链表代表的数字无前导 0
进阶:如果输入链表不能修改该如何处理?换句话说,不能对列表中的节点进行翻转。
//leetcode submit region begin(Prohibit modification and deletion)
/**
* 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) {
int l1Len = 0;
int l2Len = 0;
ListNode temp = l1;
while (temp != null) {
l1Len++;
temp = temp.next;
}
temp = l2;
while (temp != null) {
l2Len++;
temp = temp.next;
}
ListNode longNode = l1;
ListNode shortNode = l2;
int longLength = l1Len;
int shortLength = l2Len;
if (longLength < shortLength) {
longNode = l2;
shortNode = l1;
longLength = l2Len;
shortLength = l1Len;
}
boolean carry = addNext(longNode, shortNode, longLength, shortLength, 0);
if (carry) {
ListNode newNode = new ListNode(1, longNode);
return newNode;
} else {
return longNode;
}
}
private boolean addNext(ListNode longNode, ListNode shortNode, int longLength, int shortLength, int curIndex) {
if (curIndex == longLength - 1) {
int sum = shortNode != null ? shortNode.val : 0;
sum += longNode.val;
longNode.val = sum % 10;
return sum >= 10;
} else if (curIndex >= (longLength - shortLength)) {
int sum = shortNode.val;
sum += longNode.val;
boolean nextCarry = addNext(longNode.next, shortNode.next, longLength, shortLength, curIndex + 1);
if (nextCarry) {
sum++;
}
longNode.val = sum % 10;
return sum >= 10;
} else {
int sum = longNode.val;
boolean nextCarry = addNext(longNode.next, shortNode, longLength, shortLength, curIndex + 1);
if (nextCarry) {
sum++;
}
longNode.val = sum % 10;
return sum >= 10;
}
}
}
//leetcode submit region end(Prohibit modification and deletion)