题解 | #链表相加(二)#
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b?tpId=295&tqId=1008772&ru=/exam/company&qru=/ta/format-top101/question-ranking&sourceUrl=%2Fexam%2Fcompany
function reverse(head){ if(head===null) return head; let pre=null; let cur=head; let next=null while(cur){ next=cur.next; cur.next=pre; pre=cur; cur=next; } head=pre; return head; } function addInList(head1,head2){ if(head1===null) return head2; if(head2===null) return head1; let l1=reverse(head1); let l2=reverse(head2); let dum=new ListNode(-1); let p=dum; let ca=0; while(l1||l2){ let sum=ca; if(l1){ sum+=l1.val; l1=l1.next; } if(l2){ sum+=l2.val; l2=l2.next; } ca=Math.floor(sum/10); let val=sum%10; p.next=new ListNode(val); p=p.next; } if(ca>0) p.next=new ListNode(ca); return reverse(dum.next); } module.exports = { addInList : addInList };