[445] 两数相加 II

85 阅读1分钟

思路:

利用进栈出栈的思想,反转链表,相加,新建链表指向余数

/*
 * @lc app=leetcode.cn id=445 lang=javascript
 *
 * [445] 两数相加 II
 */

// @lc code=start
/**
 * 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 = [],
    stack2 = []
  while (l1 !== null) {
    stack1.push(l1.val)
    l1 = l1.next
  }
  while (l2 !== null) {
    stack2.push(l2.val)
    l2 = l2.next
  }
  // carry表示超过10 就变成1,
  let carry = 0,
    curr = null
  while (stack1.length !== 0 || stack2.length !== 0) {
    let sum = 0
    //拿到数组的最后一位进行相加
    if (stack1.length !== 0) sum += stack1.pop()
    if (stack2.length !== 0) sum += stack2.pop()
    //判断是不是上一次相加是否超过10
    sum += carry
    // 取余
    const node = new ListNode(sum % 10)
    // 取小数点前,1或0
    carry = Math.floor(sum / 10)
    // 新建链表指向这个余数
    node.next = curr
    curr = node
  }
  // 判断有没有1,有就将其追加到链表最前面
  if (carry) {
    const node = new ListNode(carry)
    node.next = curr
    curr = node
  }
  return curr
}
// @lc code=end