一、题目

二、思路
- 与 力扣 2. 两数相加 的差别就在于现在这两个非负整数并不是 逆序 存储的,因此需要在力扣 2. 两数相加 的基础上首先进行反转链表(见 力扣206.反转链表)
- 加法运算是从低位开始,向高位进位,因此需要将两个链表进行反转,再进行对齐后的相加操作。
三、题解
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode ans;
l1 = reverseList(l1);
l2 = reverseList(l2);
return reverseList(addTwo(l1, l2, 0));
}
public ListNode reverseList(ListNode head) {
ListNode pre = null, cur = head;
while (cur != null) {
ListNode tmp = cur.next;
cur.next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
public ListNode addTwo(ListNode l1, ListNode l2, int carry) {
if (l1 == null && l2 == null) {
return carry != 0 ? new ListNode(carry) : null;
}
if (l1 == null) {
l1 = l2;
l2 = null;
}
int sum = l1.val + (l2 != null ? l2.val : 0) + carry;
l1.val = sum % 10;
l1.next = addTwo(l1.next, l2 != null ? l2.next : null, sum / 10);
return l1;
}
}