题解 | 链表相加(二)
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
/* * function ListNode(x){ * this.val = x; * this.next = null; * } */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * [9,3,7],[6,3] * {1,0,0,0} * * @param head1 ListNode类 * @param head2 ListNode类 * @return ListNode类 */ function addInList(head1, head2) { // write code here h1 = reverse(head1); h2 = reverse(head2); let res = null; // 记录整个链表 let head = null; // 保存链表的头部 let jinwei = 0; while (h1 || h2) { let x1 = h1 ? h1.val : 0; let x2 = h2 ? h2.val : 0; let sum = x1 + x2 + jinwei; jinwei = Math.floor(sum / 10); // 存储结果 if (res) { res.next = new ListNode(sum % 10); res = res.next; } else { // 需要存储头部 res = head = new ListNode(sum % 10); } h1 = h1 ? h1.next : null; h2 = h2 ? h2.next : null; } if (jinwei) { res.next = new ListNode(jinwei); } return reverse(head); } module.exports = { addInList: addInList, }; // 反转链表 function reverse(head) { let pre = null; let next = null; while (head) { next = head.next; head.next = pre; pre = head; head = next; } return pre; }