BM11 链表相加(二)
/*
* function ListNode(x){
* this.val = x;
* this.next = null;
* }
*/
/**
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
function addInList(head1, head2) {
// write code here
// 先倒序两个链表
let reHead1 = reverseList(head1);
let reHead2 = reverseList(head2);
let head = new ListNode(0);
let sumHead = head;
// 是否有进位
let exceed = 0;
// 循环相加倒序后的链表(也就是从个位开始加)
// 记录是否有进位并相加进位
while (reHead1 || reHead2) {
sumHead.next = new ListNode(0);
const val1 = parseInt(reHead1 ? reHead1.val : 0);
const val2 = parseInt(reHead2 ? reHead2.val : 0);
const sum = val1 + val2 + exceed;
if (sum >= 10) {
sumHead.next.val = sum % 10;
exceed = 1;
} else {
sumHead.next.val = sum;
exceed = 0;
}
reHead1 = reHead1 ? reHead1.next : null;
reHead2 = reHead2 ? reHead2.next : null;
sumHead = sumHead.next;
}
// 有进位就再加一个进位
if (exceed) {
sumHead.next = new ListNode(exceed);
}
// 最后将新链表翻转
const reSum = reverseList(head.next);
return reSum;
}
function reverseList(head) {
let prev = null;
let curr = head;
while (curr) {
[curr.next, curr, prev] = [prev, curr.next, curr];
}
return prev;
}
module.exports = {
addInList: addInList,
};
如有问题望指正

京公网安备 11010502036488号