image.png

题解

  1. /**
  2. * Definition for singly-linked list.
  3. * class ListNode {
  4. * val: number
  5. * next: ListNode | null
  6. * constructor(val?: number, next?: ListNode | null) {
  7. * this.val = (val===undefined ? 0 : val)
  8. * this.next = (next===undefined ? null : next)
  9. * }
  10. * }
  11. */
  12. function addTwoNumbers(l1: ListNode | null, l2: ListNode | null): ListNode | null {
  13. // 头节点 当前节点
  14. let head = null; let target = null;
  15. // 累加值 传递到下一次循环
  16. let carry = 0;
  17. while (l1 || l2) {
  18. let val1 = l1 && l1.val || 0;
  19. let val2 = l2 && l2.val || 0;
  20. let sum = val1 + val2 + carry;
  21. // 判断是否第一次
  22. if (!head) {
  23. head = target = new ListNode(sum % 10);
  24. } else {
  25. target.next = new ListNode(sum % 10);
  26. target = target.next;
  27. }
  28. // 重置累加值
  29. carry = Math.floor(sum / 10);
  30. if (l1) {
  31. l1 = l1.next;
  32. }
  33. if (l2) {
  34. l2 = l2.next;
  35. }
  36. }
  37. // 此时如果carry > 0 说明要加一位 也就是新加一个节点
  38. if (carry > 0) {
  39. target.next = new ListNode(carry);
  40. }
  41. return head;
  42. };

相似题目

image.png

思路

解法与上题相似,不过反过来了, 我们可以通过两个栈(stack)来记录遍历两条链表的值,
通过一个max变量 比较两个栈的大小 取最大值进行遍历,从尾部构建出整个链表。

代码

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

function addTwoNumbers(l1: ListNode | null, l2: ListNode | null): ListNode | null {
    let target = null;
    let a = null;
    let stack1 = [], stack2 = [];
    while (l1) {
        stack1.push(l1.val);
        l1 = l1.next;
    }
    while (l2) {
        stack2.push(l2.val);
        l2 = l2.next;
    }

    let carry = 0;
    let arr = [];
    let sum = 0;
    let max = Math.max(stack1.length, stack2.length);
    for (let i = 0; i < max; i++) {
        let val1 = stack1.pop() || 0;
        let val2 = stack2.pop() || 0;
        sum = val1 + val2 + carry;
        a = new ListNode(sum % 10);
        a.next = target;
        target = a;
        carry = Math.floor(sum / 10);
    }
    let x = null;
    if (carry > 0) {
        x = new ListNode(carry);
        x.next = target;
        console.log(x.val);
    }
    console.log(target.val);
    return target ? carry ? x : target : null;
};