2. Add Two Numbers
将两个链表相加,每个链表尾部是数字的最高位
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int sum = 0;
ListNode head = new ListNode(0);
ListNode tail = head;
while (l1 != null || l2 != null) {
sum /= 10;
if (l1 != null) {
sum += l1.val;
l1 = l1.next;
}
if (l2 != null) {
sum += l2.val;
l2 = l2.next;
}
tail.next = new ListNode(sum % 10);
tail = tail.next;
}
if (sum / 10 != 0) {
tail.next = new ListNode(1);
}
return head.next;
}
445. Add Two Numbers II
将两个链表相加,链表第一位是数字的最高位
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7
有两种方法:使用stack或者递归
- 用stack就是分别储存两个链表的值,再取出来相加
- 用递归要首先知道两个链表的长度差值,然后长的链表先递归,直到剩下链表长度和短的相等后,两个链表一起递归
- 递归到最后一位时将两个链表相加,并返回进位值,不断向上层回溯最后得到解,下面是递归方法代码
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode c1 = l1, c2 = l2;
int len1 = 0, len2 = 0;
while (c1 != null) {
len1++;
c1 = c1.next;
}
while (c2 != null) {
len2++;
c2 = c2.next;
}
ListNode nl1 = null, nl2 = null;
if (len1 >= len2) {
nl1 = l1;
nl2 = l2;
} else {
nl1 = l2;
nl2 = l1;
}
ListNode head = new ListNode(0);
int mark = addNode(nl1, nl2, Math.abs(len1 - len2), head);
if (mark != 0) {
ListNode temp = new ListNode(1);
temp.next = head.next;
head.next = temp;
}
return head.next;
}
public int addNode(ListNode l1, ListNode l2, int diff, ListNode head) {
if (diff > 0) {
int mark = addNode(l1.next, l2, diff - 1, head);
int sum2 = mark + l1.val;
mark = sum2 / 10;
ListNode temp = new ListNode(sum2 % 10);
temp.next = head.next;
head.next = temp;
return mark;
}
if (l1 == null && l2 == null)
return 0;
int mark = addNode(l1.next, l2.next, diff, head);
int sum = l1.val + l2.val + mark;
mark = sum / 10;
ListNode temp = new ListNode(sum % 10);
temp.next = head.next;
head.next = temp;
return mark;
}