leetcode-0002 两数相加

题目地址 https://leetcode-cn.com/problems/add-two-numbers/git

1. 链表遍历操做

时间复杂度O(n) 空间复杂度O(n)github

var addTwoNumbers = function(l1, l2) {
    // 定义一个虚拟头节点,加入虚拟头节点的目的主要是避免在链表中添加节点时区分是不是头节点
    // 好比这里若是不用头节点,咱们就得区分curr节点是否为空,若是为空拿curr直接赋值
    // 若是不为空,须要对curr.next进行赋值
    const dummyHead = new ListNode(null)
    let curr =dummyHead
    let carry = 0
    
    while (l1 !== null || l2 !== null || carry === 1) {
        const num1 = l1 === null ? 0 : l1.val
        const num2 = l2 === null ? 0 : l2.val
        const sum = num1 + num2 + carry

        // 这里是整个循环最重要的两步
        // 1. 将当前节点的next指向新的节点
        // 2. 移动curr指针到下一个节点
        curr.next = new ListNode(sum % 10)
        curr = curr.next

        l1 = l1 === null ? null : l1.next
        l2 = l2 === null ? null : l2.next
        carry = sum >= 10 ? 1 : 0
    }
    return dummyHead.next
};

更多leetcode题解和数据结构方面的知识,请关注个人github:https://github.com/GuoLizhi/数据结构

相关文章
相关标签/搜索