题解 | #链表相加(二)# 相加后重建链表

链表相加(二)

https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b

function addInList(head1, head2) {
    let l1 = [], l2 = [], l3 = []
    let cur = head1
    while (cur) {
        l1.push(cur.val)
        cur = cur.next
    }
    cur = head2
    while (cur) {
        l2.push(cur.val)
        cur = cur.next
    }
    l3 = add(l1, l2)
    let dummy = new ListNode(0)
    cur = dummy
    for (let v of l3) {
        let node = new ListNode(v)
        cur.next = node
        cur = cur.next
    }
    return dummy.next
}

function add(a1, a2) {
    let res = []
    let i = a1.length - 1, j = a2.length - 1, m = 0
    while (i >= 0 || j >= 0 || m !== 0) {
        let x = i >= 0 ? a1[i] : 0
        let y = j >= 0 ? a2[j] : 0
        let s = x + y + m
        res.push(s % 10)
        m = Math.floor(s / 10)
        i--
        j--
    }
    return res.reverse()
};

module.exports = {
    addInList: addInList,
};

全部评论

相关推荐

我见java多妩媚:大外包
点赞 评论 收藏
分享
牛客5655:其他公司的面试(事)吗
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务