Skip to content
文档章节

BM11 链表相加(二)

描述

假设链表中每一个节点的值都在 0 - 9 之间,那么链表整体就可以代表一个整数。

给定两个这种链表,请生成代表两个整数相加值的结果链表。

数据范围:0 \le n,m \le 10000000≤n,m≤1000000,链表任意值 0 \le val \le 90≤val≤9要求:空间复杂度 O(n)O(n),时间复杂度 O(n)O(n)

例如:链表 1 为 9->3->7,链表 2 为 6->3,最后生成新的结果链表为 1->0->0->0。 BM11

备注:

1 \leq n, m \leq 10^61≤n,m≤1060 \leq a_i, b_i \leq 90≤ai,bi≤9

示例1

输入:

[9,3,7],[6,3]

返回值:

{1,0,0,0}

说明:

如题面解释

示例2

输入:

[0],[6,3]复制

返回值:

{6,3} 复制

ts
/*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)
 *     }
 * }
 */

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * @param head1 ListNode类
 * @param head2 ListNode类
 * @return ListNode类
 */
export function addInList(head1: ListNode, head2: ListNode): ListNode {
  // write code here
  var digit = 1;
  var num1 = [];
  var num2 = [];
  while (head1) {
    num1.push(head1.val);
    head1 = head1.next;
  }
  while (head2) {
    num2.push(head2.val);
    head2 = head2.next;
  }

  var mod = 10;
  var head = new ListNode();
  var uppre = 0;
  while (num1.length && num2.length) {
    var total = num1.pop() + num2.pop() + uppre;
    uppre = Math.floor(total / 10);
    var val = total % 10;
    var node = new ListNode(val);
    if (head.next) node.next = head.next;
    head.next = node;
  }

  while (num1.length) {
    var total = num1.pop() + uppre;
    uppre = Math.floor(total / 10);
    var val = total % 10;
    var node = new ListNode(val);
    if (head.next) node.next = head.next;

    head.next = node;
  }

  while (num2.length) {
    var total = num2.pop() + uppre;
    uppre = Math.floor(total / 10);
    var val = total % 10;
    var node = new ListNode(val);
    if (head.next) node.next = head.next;

    head.next = node;
  }

  if (uppre) {
    var node = new ListNode(uppre);
    if (head.next) node.next = head.next;

    head.next = node;
  }

  return head.next;
}