Published
Edited
Oct 7, 2022
1 star
Insert cell
Insert cell
Insert cell
class SingleLinkedNode {
constructor(data) {
this.next = null
this.data = data
}

toString() {
let node = this
let values = []
while (node !== null) {
values.push(node.data)
node = node.next
}
return values.join(' ')
}
}
Insert cell
function getSortedListNode(arr) {
arr.sort((a, b) => a - b)
let head = new SingleLinkedNode(arr[0])
let current = head
for (let i = 1; i < arr.length; ++i) {
current = current.next = new SingleLinkedNode(arr[i])
}
return head
}
Insert cell
getSortedListNode([2, 512, 2, 5, 7, 3]).toString()
Insert cell
Insert cell
function getSmallestAndForward(p1, p2) {
if (p1 === null || (p2 !== null && p2.data < p1.data)) {
return {
p1: p1,
p2: p2.next,
value: p2.data
}
}
return {
p1: p1.next,
p2: p2,
value: p1.data
}
}
Insert cell
function merge(head1, head2) {
let p1, p2, value
({ p1, p2, value } = getSmallestAndForward(head1, head2))
let head = new SingleLinkedNode(value)
let current = head
while (p1 || p2) {
({ p1, p2, value } = getSmallestAndForward(p1, p2))
current = current.next = new SingleLinkedNode(value)
}
return head
}
Insert cell
merge(getSortedListNode([6, 2, 7]), getSortedListNode([9, 6, 2, 5, 9, 11])).toString()
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more