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

链表相加(二)

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

/*
 * function ListNode(x){
 *   this.val = x;
 *   this.next = null;
 * }
 */
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param head1 ListNode类 
 * @param head2 ListNode类 
 * @return ListNode类
 */
function addInList( head1 ,  head2 ) {
    // write code here
    let p1 = head1
    let p2 = head2
    p1 = reverseNode(p1)
    
    p2 = reverseNode(p2)
    let p3 = new ListNode(0)
    let current = p3
    while (p1 || p2) {
        let n1 = (p1 === null)?  0 :  p1.val
        let n2 = (p2 === null)?  0 :  p2.val
        if((n1+n2+current.val)>=10) {
            current.next = new ListNode(1)
            current.val = (n1+n2+current.val)%10
        }
        else {
            current.next = new ListNode(0)
            current.val = n1+n2+current.val
        }
        if(p1 !== null) {
            p1 = p1.next
        }
        if(p2 !== null) {
            p2 = p2.next
        }
        current = current.next
    }
    return reverseNode(p3).next
}
function reverseNode (head) {
    let p1 = head
    let left = null
    while (p1) {
        let tem = p1.next
        p1.next = left
        left = p1
        p1 = tem
    }
    return left
}
module.exports = {
    addInList : addInList
};

全部评论

相关推荐

牛客60022193...:大厂都招前端,他们觉得AI能替代前端,可能他们公司吊打btaj吧
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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