https://leetcode-cn.com/problems/add-two-numbers-ii/
点击查看【bilibili】

题目

给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。

你可以假设除了数字 0 之外,这两个数字都不会以零开头。
进阶:
如果输入链表不能修改该如何处理?换句话说,你不能对列表中的节点进行翻转

示例

  1. 入:(7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
  2. 输出:7 -> 8 -> 0 -> 7

解答

image.png

答案

  1. var addTwoNumbers = function(l1, l2) {
  2. const stack1 = [], stack2= [];
  3. while(l1 !==null) {
  4. stack1.push(l1.val)
  5. l1 = l1.next
  6. }
  7. while(l2 !== null) {
  8. stack2.push(l2.val)
  9. l2 = l2.next
  10. }
  11. let carry=0,curr=null
  12. while(stack1.length !==0 || stack2.length !==0) {
  13. let sum = 0;
  14. if(stack1.length!==0) {
  15. sum += stack1.pop()
  16. }
  17. if(stack2.length!==0) {
  18. sum += stack2.pop()
  19. }
  20. sum += carry
  21. const node = new ListNode(sum % 10)
  22. carry = Math.floor(sum / 10)
  23. node.next = curr
  24. curr = node
  25. }
  26. if(carry !== 0) {
  27. const node = new ListNode(carry)
  28. node.next = curr
  29. curr = node
  30. }
  31. return curr
  32. };