leetcode-0002 两数相加

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

1. 链表遍历操作

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

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/

posted @ 2020-04-17 16:27  郭励之  阅读(105)  评论(0编辑  收藏  举报