牛客题霸——两个链表生成相加链表(Javascript)

一、题目链接

https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b?tpId=117

二、思路链接

https://www.bilibili.com/video/BV1Ey4y177ve?t=318

三、具体代码

/*
 * function ListNode(x){
 *   this.val = x;
 *   this.next = null;
 * }
 */

/**
 * 
 * @param head1 ListNode类 
 * @param head2 ListNode类 
 * @return ListNode类
 */
function addInList( head1 ,  head2 ) {
    let s1 = [], s2 = [];
    //将head1的元素放入栈1
    while(head1) {
        s1.push(head1.val);
        head1 = head1.next;
    }
    //将head2的元素放入栈2
    while(head2) {
        s2.push(head2.val);
        head2 = head2.next;
    }
    //如果两个值的加和大于10,就会产生进位,cnt用来存储进位
    let cnt = 0;
    let res = null; //定义结果指针
    while(s1.length !== 0 || s2.length !== 0) {
        let x1 = s1.length === 0 ? 0 :s1.pop();
        let x2 = s2.length === 0 ? 0 :s2.pop();
        let sum = x1 + x2 + cnt;//当前这一位的相加总和
        cnt = Math.floor(sum / 10);//更新当前加和是否有进位
        //进行当前节点的插入
        let tempNode = new ListNode(Math.floor(sum % 10));
        tempNode.next = res;
        res = tempNode;
    }
    //最后一位的时候,还得判断当前是否有进位,如果有进位,就得将进位插入到最前面
    if(cnt > 0) {
        let tempNode = new ListNode(cnt);
        tempNode.next = res;
        res = tempNode;
    }
    return res;
}
module.exports = {
    addInList : addInList
};
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值