如何在本机运行链表程序? 当我在输入框中运行此代码时,它正在运行,但我似乎无法在本地计算机中运行此程序。
function ListNode(val, next) {
this.val = (val===undefined ? 0 : val)
this.next = (next===undefined ? null : next)
}
/**
* @param {ListNode} list1
* @param {ListNode} list2
* @return {ListNode}
*/
var mergeTwoLists = function (l1, l2) {
var mergedHead = { val: -1, next: null },
crt = mergedHead;
while (l1 && l2) {
if (l1.val > l2.val) {
crt.next = l2;
l2 = l2.next;
} else {
crt.next = l1;
l1 = l1.next;
}
crt = crt.next;
}
crt.next = l1 || l2;
return mergedHead.next;
};
mergeTwoLists([1, 2, 4], [1, 3, 4]);
您可以使用这两个辅助函数将数组转换为链表,反之亦然,这本质上是 LeetCode 框架在幕后为您所做的事情。
const listFromArray = a => a.length ? new ListNode(a[0], listFromArray(a.slice(1)))
: null;
const arrayFromList = head => head ? [head.val].concat(arrayFromList(head.next))
: [];
在您的情况下,您可以像这样使用它们:
const result = arrayFromList(
mergeTwoLists(listFromArray([1, 2, 4]), listFromArray([1, 3, 4]))
);
我能够通过提供我生成的
mergeTwoLists
和 ListNode
类在本地运行 LinkedList
方法。如下所示,runCase
辅助函数采用两个ListNodes
(LinkedList
头),将它们合并并打印结果。我们可以使用 toArray
和 LeetCode 测试用例输入创建一个链表,并使用 fromArray
的 LinkedList
函数将结果转换为数组。
class ListNode {
constructor(val=0, next=null) {
this.val = val;
this.next = next;
}
}
class LinkedList {
constructor(head = null) {
this.head = head
}
static fromArray(array) {
const linkedList = new LinkedList();
for (let i = array.length - 1; i >= 0; i--) {
const node = new ListNode(array[i]);
node.next = linkedList.head;
linkedList.head = node;
}
return linkedList;
}
toArray() {
const array = [];
let current = this.head;
while (current) {
array.push(current.val);
current = current.next;
}
return array;
}
}
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*
* @param {ListNode} node1
* @param {ListNode} node2
* @return {ListNode}
*/
var mergeTwoLists = function(node1, node2) {
let linkedList = new LinkedList(),
current = linkedList;
while (node1 && node2) {
if (node1.val > node2.val) {
current.next = node2;
node2 = node2.next;
} else {
current.next = node1;
node1 = node1.next;
}
current = current.next;
}
current.next = node1 || node2;
return linkedList.next;
};
const runCase = (array1, array2) => {
const node1 = LinkedList.fromArray(array1).head;
const node2 = LinkedList.fromArray(array2).head
const result = mergeTwoLists(node1, node2);
const linkedList = new LinkedList(result);
console.log(linkedList.toArray());
}
runCase([1, 2, 4], [1, 3, 4]); // [1,1,2,3,4,4]
runCase([], []); // []
runCase([], [0]); // [0]