题解 | #链表相加(二)#
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
function ReverseList(pHead){
if(pHead == null || pHead.next == null){
return pHead;
}
let pre = null;
let cur = pHead;
let next = null;
while(cur != null){
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
function addInList( head1 , head2 ) {
head1 = ReverseList(head1);
head2 = ReverseList(head2);
let carry = 0;
let dummy = new ListNode(0);
let cur = dummy;
while(head1 != null || head2 != null){
let sum = carry;
if(head1 != null){
sum += head1.val;
head1 = head1.next;
}
if(head2 != null){
sum += head2.val;
head2 = head2.next;
}
carry = Math.floor(sum / 10);
sum = sum % 10;
cur.next = new ListNode(sum);
cur = cur.next;
}
if(carry != 0){
cur.next = new ListNode(carry);
}
return ReverseList(dummy.next);
}