/* * 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 str1 = ‘‘; let str2 = ‘‘; let count1 = 0; let count2 = 0; while(head1){ str1 += head1.val; head1 = head1.next; count1++; } while(head2){ str2 += head2.val; head2 = head2.next; count2++; } let max = count1 > count2 ? count1: count2; str1 = str1.padStart(max,‘0‘) str2 = str2.padStart(max,‘0‘) let f = 0 //进位 let cur = ‘‘ //暂存值 for(let i = max-1;i>=0;i--){ let tmp = Number(str1[i])+Number(str2[i]) + f; f = Math.floor(tmp / 10); cur = tmp % 10 + cur; } // 最后一位是否进位 cur = f ? `1${cur}` : cur; var curs = new ListNode(-1); var dummy = curs; for(let i = 0;i<cur.length;i++){ var temp = new ListNode(cur[i]); dummy.next = temp; dummy = temp; } return curs.next; } // //翻转链表操作 // function reverseList(head){ // var pre = null // var low = null // while(head){ // low = head.next; // head.next = pre; // pre = head; // head = low; // } // return pre; // } module.exports = { addInList : addInList };
原文:https://www.cnblogs.com/taue997/p/14855223.html