题目链接
法一
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = new ListNode(0);
ListNode cursor = head;
int sum = 0;
while (l1 != null || l2 != null || sum != 0) {
if (l1 != null) {
sum += l1.val;
l1 = l1.next;
}
if (l2 != null) {
sum += l2.val;
l2 = l2.next;
}
cursor.next = new ListNode(sum % 10);
cursor = cursor.next;
sum /= 10;
}
return head.next;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
本地测试
lay.showTitle(2);
Solution2 sol2 = new Solution2();
ListNode head2_1 = new ListNode();
ListNode head2_2 = new ListNode();
int[] nums2_1 = new int[]{2,4,3};
int[] nums2_2 = new int[]{5,6,4};
head2_1 = listOpt.creatListByArray(head2_1, nums2_1);
head2_2 = listOpt.creatListByArray(head2_2, nums2_2);
listOpt.showList(head2_1);
listOpt.showList(head2_2);
ListNode head2 = sol2.addTwoNumbers(head2_1.next, head2_2.next);
listOpt.showNoHeadList(head2);