题解 | #链表相加(二)#
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
public ListNode addInList (ListNode head1, ListNode head2) {
ListNode overHead1 = overList(head1);
ListNode overHead2 = overList(head2);
ListNode head = new ListNode(0);
ListNode index = head;
int carry = 0;
int sum = 0;
int val = 0;
while (overHead1 != null || overHead2 != null) {
if (overHead1 == null) {
sum = overHead2.val + carry;
overHead2 = overHead2.next;
} else if (overHead2 == null) {
sum = overHead1.val + carry;
overHead1 = overHead1.next;
} else {
sum = overHead1.val + overHead2.val + carry;
overHead1 = overHead1.next;
overHead2 = overHead2.next;
}
val = sum % 10;
carry = sum / 10;
index.next = new ListNode(val);
index = index.next;
}
if (carry != 0) {
index.next = new ListNode(carry);
index = index.next;
}
return overList(head.next);
}
private ListNode overList(ListNode head) {
if (head == null) {
return head;
}
ListNode node = null, cur = head;
while (cur != null) {
ListNode tail = cur.next;
cur.next = node;
node = cur;
cur = tail;
}
return node;
}
}

查看18道真题和解析