Here's some quick code I used to set up a quick array of linked lists for a leetcode problem - Merge K Sorted Lists.
Converting arrays to singly-linked LinkedLists (without head or tail).
1
/**
2
* Definition for singly-linked list.
3
* function ListNode(val) {
4
* this.val = val;
5
* this.next = null;
6
* }
7
*/
8
9
let ListNode = function(value) {
10
this.value = value;
11
this.next = null;
12
13
this.connect = (node) => {
14
this.next = node;
15
return this;
16
}
17
}
18
19
let convertArray = (array) => {
20
let nodeMap = array.map((x) => new ListNode(x));
21
22
return nodeMap.map((x, i, arr) => {
23
if (arr[i + 1]) return arr[i].connect(arr[i + 1])
24
})[0]
25
}
26
27
// Input:
28
// [
29
// 1->4->5,
30
// 1->3->4,
31
// 2->6
32
// ]
33
// Output: 1->1->2->3->4->4->5->6
34
35
let testArray = [[1, 4, 5], [1, 3, 4], [2, 6]]
36
testArray = testArray.map((x) => convertArray(x));