题解 | #链表相加(二)#
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
/* * function ListNode(x){ * this.val = x; * this.next = null; * } */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head1 ListNode类 * @param head2 ListNode类 * @return ListNode类 */ //链表翻转 function fanzhuan(p) { let p1 = p let p2 = null while (p1) { let temp = p1.next p1.next = p2 p2 = p1 p1 = temp } return p2 } function addInList(head1, head2) { // write code here let fHead1 = fanzhuan(head1) let fHead2 = fanzhuan(head2) let num = 0 let List=new ListNode(null) let value=List while (fHead1 || fHead2) { let a=fHead1?fHead1.val:0 let b=fHead2?fHead2.val:0 let sum=a+b+num num=parseInt(sum/10) sum=sum%10 value.next=new ListNode(sum) value=value.next if (fHead1) fHead1 = fHead1.next if (fHead2)fHead2 = fHead2.next } if(num==0){ List=fanzhuan(List.next) }else{ List.next=fanzhuan(List.next) List.val=num } return List } module.exports = { addInList: addInList };