BM11 链表相加(二)

题目描述

image

思路分析

之前做过两数相加,与这道题类似,但是那道题的相加顺序是排好的,比如:
1000+20 两个链表的排序都是从最低位开始的 0->0->0->1, 0->2 ,此时我们直接相加就可以了。
但是这道题给的条件略有不同,是反向的。因此我们可以在之前的基础上再做一个链表反转,将反转的链表传递过去
具体的上一篇链接如下:
链表相加

代码参考

function addInList( l1 ,  l2 ) {
    l1 = listReverse(l1)
    l2 = listReverse(l2)
    // write code here
    let head = new ListNode(null)
     let current = head
    //  进位
     let carry = 0
     while(carry || l1 || l2) {
         let v1 = l1?l1.val:0
         let v2 = l2?l2.val:0
         let sum = v1+v2+carry
         carry = Math.floor(sum/10)
         current.next = new ListNode(sum%10)
         current = current.next
         l1 = l1 ? l1.next : null
         l2 = l2 ? l2.next :null
     }
     return listReverse(head.next)
}
function listReverse(list) {
    if(list===null) return list
    let cur = list
    let pre = null
    while(cur){
        let tmp = cur.next
        cur.next = pre
        pre = cur
        cur = tmp
    }
    return pre
}
posted @ 2022-12-29 12:46  含若飞  阅读(29)  评论(0编辑  收藏  举报