/*
* function ListNode(x){
* this.val = x;
* this.next = null;
* }
*/
/**
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
function addInList(head1, head2) {
// write code here
// 获取反转数组
function getInv(head) {
let end = head;
cur = head;
pre = null;
while (end) {
end = end.next;
}
while (cur != end) {
let temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
// 先反转一下两个列表,方便进行累加操作
let a = getInv(head1);
let b = getInv(head2);
let list = new ListNode(0);
let ans = list;
let c = 0;
while (a || b) {
list.next = new ListNode(0);
list = list.next;
let x = 0, y = 0;
if (a != null) {
x = a.val;
a = a.next;
}
if (b != null) {
y = b.val;
b = b.next;
}
let sum = x + y + c;
if (sum > 9) {
c = parseInt(sum / 10);
sum = sum % 10;
} else {
c = 0;
}
list.val = sum;
}
// 反转最终结果列表
ans = getInv(ans.next);
// console.log("ans:", ans);
return ans;
}
module.exports = {
addInList: addInList
};