LeetCode题解|2.两数相加 - Javascript

function ListNode(val, next) {
  this.val = val === undefined ? 0 : val;
  this.next = next === undefined ? null : next;
}
function addTwoNumbers(link1, link2) {
  let l1 = link1;
  let l2 = link2;
  let result = null;
  let currentNext = null;
  let carry = 0;

  while (l1 || l2 || carry) {
    let sum = (l1?.val || 0) + (l2?.val || 0) + carry;
    carry = 0;
    if (sum >= 10) {
      carry = 1;
      sum = sum % 10;
    }
    const val = new ListNode(sum, null);
    if (result) {
      currentNext.next = val;
    } else {
      result = val;
    }
    currentNext = val;

    l1 = l1?.next;
    l2 = l2?.next;
  }
  return result;
}
addTwoNumbers(
  {
    val: 2,
    next: {
      val: 4,
      next: { val: 3, next: null },
    },
  },
  {
    val: 5,
    next: {
      val: 6,
      next: { val: 4, next: null },
    },
  }
);
addTwoNumbers(
  {
    val: 0,
    next: null,
  },
  {
    val: 0,
    next: null,
  }
);

addTwoNumbers(
  {
    val: 9,
    next: {
      val: 9,
      next: {
        val: 9,
        next: {
          val: 9,
          next: {
            val: 9,
            next: {
              val: 9,
              next: {
                val: 9,
                next: null,
              },
            },
          },
        },
      },
    },
  },
  {
    val: 9,
    next: {
      val: 9,
      next: {
        val: 9,
        next: {
          val: 9,
          next: null,
        },
      },
    },
  }
);

本文由一文多发运营工具平台 EaseWriting 发布

你可能感兴趣的:(LeetCode题解|2.两数相加 - Javascript)