import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
public ListNode addInList (ListNode head1, ListNode head2) {
// write code here
List<ListNode> nodeList1 = new ArrayList<>();
if (head1 != null) {
nodeList1.add(head1);
ListNode temp = head1;
while (true) {
ListNode next = temp.next;
if (next == null) break;
nodeList1.add(next);
temp = next;
}
}
List<ListNode> nodeList2 = new ArrayList<>();
if (head2 != null) {
nodeList2.add(head2);
ListNode temp = head2;
while (true) {
ListNode next = temp.next;
if (next == null) break;
nodeList2.add(next);
temp = next;
}
}
List<ListNode> loopList1 = new ArrayList<>();
List<ListNode> loopList2 = new ArrayList<>();
int loopNum = Math.max(nodeList1.size(), nodeList2.size());
if (nodeList1.size() > nodeList2.size()) {
loopList1.addAll(nodeList1);
loopList2.addAll(nodeList2);
} else {
loopList1.addAll(nodeList2);
loopList2.addAll(nodeList1);
}
ListNode next = null;
int count = 0;
for (int i = 1; i <= loopNum; i++) {
ListNode temp1 = loopList1.get(loopList1.size() - i);
int val1 = temp1.val;
int targetVal = 0;
int sum = 0;
if (loopList2.size() - i < 0) {
sum = val1 + count;
} else {
ListNode temp2 = loopList2.get(loopList2.size() - i);
int val2 = temp2.val;
sum = val1 + val2 + count;
}
if (sum < 10) {
count = 0;
targetVal = sum;
} else {
count = 1;
targetVal = sum - 10;
}
ListNode target = new ListNode(targetVal);
target.next = next;
next = target;
}
if(count == 1){
ListNode target = new ListNode(1);
target.next = next;
next = target;
}
return next;
}
}