数据结构与算法每日一题——链表(445. 两数相加 II)

61 阅读1分钟

445. 两数相加 II image.png

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var addTwoNumbers = function (l1, l2) {
    // 准备两个栈 分别将两个链表推入栈中
    let stack1 = []; let stack2 = []
    while (l1) {
        stack1.push(l1.val)
        l1 = l1.next
    }
    while (l2) {
        stack2.push(l2.val)
        l2 = l2.next
    }
    // 然后将栈中的数字推出来,分别进行相加
    let carry = 0; let cur = null
    while (stack1.length || stack2.length) {
        let sum = 0
        if (stack1.length) {
            sum += stack1.pop()
        }
        if (stack2.length) {
            sum += stack2.pop()
        }
        // 总数加上carry值
        sum += carry
        // 将node值总数求余取出来,因为不能进行翻转,node的值指向cur
        let node = new ListNode(sum % 10)
        // 向前进位的值
        carry = Math.floor(sum / 10)
        // 因为不能反转 所以将node值进行连接
        node.next = cur
        // 将node值赋给当前位
        cur = node
    }
    // 最后stack1中是7,stack2中是无,最后一个也要添加
    if (carry) {
        let node = new ListNode(carry)
        node.next = cur
        cur = node
    }
    return cur
};