题解 | 链表相加(二)

链表相加(二)

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

/*
 * function ListNode(x){
 *   this.val = x;
 *   this.next = null;
 * }
 */
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 * [9,3,7],[6,3]
 * {1,0,0,0}
 *
 * @param head1 ListNode类
 * @param head2 ListNode类
 * @return ListNode类
 */
function addInList(head1, head2) {
    // write code here
    h1 = reverse(head1);
    h2 = reverse(head2);
    let res = null; // 记录整个链表
    let head = null; // 保存链表的头部
    let jinwei = 0;

    while (h1 || h2) {
        let x1 = h1 ? h1.val : 0;
        let x2 = h2 ? h2.val : 0;
        let sum = x1 + x2 + jinwei;
        jinwei = Math.floor(sum / 10);

        // 存储结果
        if (res) {
            res.next = new ListNode(sum % 10);
            res = res.next;
        } else {
            // 需要存储头部
            res = head = new ListNode(sum % 10);
        }

        h1 = h1 ? h1.next : null;
        h2 = h2 ? h2.next : null;
    }

    if (jinwei) {
        res.next = new ListNode(jinwei);
    }

    return reverse(head);
}
module.exports = {
    addInList: addInList,
};

// 反转链表
function reverse(head) {
    let pre = null;
    let next = null;
    while (head) {
        next = head.next;
        head.next = pre;
        pre = head;
        head = next;
    }
    return pre;
}

全部评论

相关推荐

宇算唯航:目测实缴资本不超100W的小公司
点赞 评论 收藏
分享
06-05 19:46
已编辑
武汉大学 后端
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-10 14:10
啊啊啊啊好幸福,妈妈是我找工作发疯前的一束光
榕城小榕树:你是我见过最幸福的牛客男孩
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务