You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
/* * @Description: 445. Add Two Numbers II * @Author: libk * @Github: https://github.com/libk */ /** * 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} */ const addTwoNumbers = function(l1, l2) { let reL1 = reverseList(l1) let reL2 = reverseList(l2) let dummy = new ListNode() let cur = dummy let carry = 0
while (reL1 !== null || reL2 !== null || 1 === carry) { let sum = 0 if (reL1 !== null) { sum += reL1.val reL1 = reL1.next } if (reL2 !== null) { sum += reL2.val reL2 = reL2.next } sum += carry carry = Math.floor(sum / 10) cur.next = new ListNode(sum % 10) cur = cur.next } return reverseList(dummy.next) }
functionreverseList (head) { if (head === null) { return head } let pre = null let cur = head while (cur !== null) { let temp = cur.next cur.next = pre pre = cur cur = temp } return pre }
let cur = null let carry = 0 while (stack1.length || stack2.length || carry === 1) { let sum = 0 if (stack1.length) { sum += stack1.pop().val } if (stack2.length) { sum += stack2.pop().val } sum += carry let newHead = new ListNode(sum % 10, cur) cur = newHead carry = Math.floor(sum / 10) } return cur }