LeetCode每日一练【2】

LeetCode每日一练

add_two_numbers

/*
 * @Author: fox
 * @Date: 2022-04-19 17:30:35
 * @LastEditors: fox
 * @LastEditTime: 2022-04-19 19:01:44
 * @Description: https://leetcode.com/problems/add-two-numbers/
 */
class ListNode {
    constructor(val, next) {
        this.val = (val === undefined ? 0 : val);
        this.next = (next === undefined ? null : next);
    }
}
/**
 * @description: 
 * @param {ListNode} l1 链表1
 * @param {ListNode} l2 链表2
 * @return {ListNode}
 */
const addTwoNumbers = (l1, l2) => {
    let carry = 0   // 计算和的进位
    let current = new ListNode() // 创建一个ListNode链表对象
    const listnode = current // 缓存ListNode链表的头节点
    while (l1 || l2) {
        if (l1) {
            carry += l1.val
            l1 = l1.next
        }
        if (l2) {
            carry += l2.val
            l2 = l2.next 
        }

        // 存储值到新创建的链表中
        current.next = new ListNode(carry % 10)
        // 切断当前节点到当前节点的下一个节点
        current = current.next

        // 更新进位,如果大于9,则将进位设置为1,否则设置为0
        carry = carry > 9 ? 1 : 0 
    }

    // 进位溢出,当l1和l2都已经计算完毕后,将溢出的进位放进当前节点的下一个节点中
    if (carry) current.next = new ListNode(carry)

    // 返回根节点后面所有的节点,因为根节点是为初始值,并不是我们所需要的
    return listnode.next
}
posted @ 2022-04-19 19:05  白い故雪  阅读(12)  评论(0编辑  收藏  举报