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

链表相加(二)

https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b?tpId=295&tqId=1008772&ru=/exam/company&qru=/ta/format-top101/question-ranking&sourceUrl=%2Fexam%2Fcompany


  function reverse(head){
    if(head===null) return head;
        let pre=null;
        let cur=head;
        let next=null
        while(cur){
            next=cur.next;
            cur.next=pre;
            pre=cur;
            cur=next;
        }
            head=pre;
            return head;       
    }


function addInList(head1,head2){
    if(head1===null) return head2;
    if(head2===null) return head1;

    let l1=reverse(head1);
    let l2=reverse(head2);

    let dum=new ListNode(-1);
    let p=dum;

    let ca=0;

    while(l1||l2){
        let sum=ca;
        if(l1){
            sum+=l1.val;
            l1=l1.next;
        }
          if(l2){
            sum+=l2.val;
            l2=l2.next;
        }
        ca=Math.floor(sum/10);
        let val=sum%10;
        p.next=new ListNode(val);
        p=p.next;

    }
    if(ca>0) p.next=new ListNode(ca);
    return reverse(dum.next); 
}



module.exports = {
    addInList : addInList
};

全部评论

相关推荐

04-29 18:07
常州大学 Java
寂静羽翼:兄弟我已经亲身经历了,双非没实习很多大厂还是会给笔试的,可是有的公司笔试做的好也不给面一直卡着,ssob基本看我没实习都拒绝我了,但是每天投满偶尔也能有一两场初创公司的面试,但是薪资基本在五六千
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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