题解 | #链表相加(二)#

链表相加(二)

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

/*
 * function ListNode(x){
 *   this.val = x;
 *   this.next = null;
 * }
 */
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 *
 * @param head1 ListNode类
 * @param head2 ListNode类
 * @return ListNode类
 */
function ReverseList(head) {
    let pre = null,
        cur = head;
    while (cur) {
        let temp = cur;
        cur = cur.next;
        temp.next = pre;
        pre = temp;
    }
    return pre;
    // write code here
}
function addInList(head1, head2) {
    function ReverseList(head) {
        let pre = null,
            cur = head;
        while (cur) {
            let temp = cur;
            cur = cur.next;
            temp.next = pre;
            pre = temp;
        }
        return pre;
        // write code here
    }
    head1 = ReverseList(head1);
    head2 = ReverseList(head2);
    let n = 0,
        arr = [];
    while (head1 || head2) {
        let add = (head1 ? head1.val : 0) + (head2 ? head2.val : 0) + n;
        if (head1) head1 = head1.next;
        if (head2) head2 = head2.next;
        n = 0;
        if (add >= 10) {
            add = add - 10;
            n = 1;
        }
        arr.push(add);
    }
    if (n === 1) arr.push(1);
    let head = new ListNode(arr.pop());
    let tail = head;
    while (arr.length) {
        tail.next = new ListNode(arr.pop());
        tail = tail.next;
    }

    return head;
    // write code here
}
module.exports = {
    addInList: addInList,
};

全部评论

相关推荐

牛客48826091...:哥们胸肌挺好看
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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