牛客题霸——两个链表生成相加链表(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
};
上一篇:C/C++补充材料·头文件与代码文件与inline


下一篇:十大经典排序之桶排序(C++实现)