是否可以在 javascript 中将 Array 转换为 NodeList? leetcode问题--链表--

is it possible to convert an Array to a NodeList in javascript? leetcode problem --Linked lists--

我正在尝试解决一个 leetcode 问题,我想我已经弄明白了,问题是我的函数 return 是一个具有正确答案的数组,问题指定我必须 return 一个节点列表,

我不知道如何在不到达 DOM 的情况下创建 NodeList,或者如何将我的 Array 转换为 NodeList。

问题是:

Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists.

Example:

Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4

我的代码是:

const listOne = [1, 2, 4];
const listTwo = [1, 3, 4];

function myFunction(l1, l2) {
  let lslength;
  let newList = [];
  if (l1.length >= l2.length) {
    lslength = l1.length;
  } else {
    lslength = l2.length;
  }
  for (let i = 0; i < lslength; i++) {
    if (l1[i] === l2[i]) {
      newList.push(l1[i]);
      newList.push(l2[i]);
    } else if (l1[i] < l2[i]) {
      newList.push(l1[i]);
      newList.push(l2[i]);
    } else if (l1[i] > l2[i]) {
      newList.push(l2[i]);
      newList.push(l1[i]);
    } else if (l1[i]) {
      newList.push(l1[i]);
    } else {
      newList.push(l2[i]);
    }
  }
  return newList;
}

myFunction(listOne, listTwo);

--------编辑-------- 好的,所以我真的不明白这个问题,因为它是关于链表的,现在我知道了,谢谢

你不需要那样做。

我想测试用例以数组形式表示是为了简化用户操作。但是,LinkedList 和数组是两种不同的数据类型。您的函数正在返回一个数组,这不是此处所需的输出。所需的输出只是一个合并的链表,而不是一个合并的数组。

这里我们将使用哨兵节点来合并两个链表。这将被接受:

/**
 * 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 mergeTwoLists = function(l1, l2) {
    var sentinel = {
        val: -1,
        next: null
    };

    var curr = sentinel;
    while (l1 && l2) {
        if (l1.val > l2.val) {
            curr.next = l2;
            l2 = l2.next;
        } else {
            curr.next = l1;
            l1 = l1.next;
        }
        curr = curr.next;
    }

    curr.next = l1 || l2;

    return sentinel.next;
};

参考资料