Good evening! Here's our prompt for today.
Write an algorithm to merge two sorted linked lists and return it as a new sorted list. The new list should be constructed by joining the nodes of the input lists.

You may assume the following node definition:
1function Node(val) {
2 this.value = val;
3 this.next = null;
4}
5
6const list1 = new Node(1);
7list1.next = new Node(2);
8
9console.log(list1);
Write a method called mergeSortedLists
that would be invoked as such in the following example:
1// List 1: 1 -> 5 -> 6
2// List 2: 2 -> 3 -> 4
3
4mergeSortedLists(list1, list2);
5// Output: 1 -> 2 -> 3 -> 4 -> 5 -> 6
As you can see, the linked lists are merged in an ascending sorted order.
Constraints
- Length of the linked lists <=
100000
- The values in the nodes will be in the range
-1000000000
and1000000000
- Expected time complexity :
O(n)
- Expected space complexity :
O(n)
considering the call stack in recursion
Try to solve this here or in Interactive Mode.
How do I practice this challenge?
xxxxxxxxxx
106
'PASSED: Expect `mergeSortedLists(2 -> 6 -> 9, 1 -> 2 -> 7)` to return 1 -> 2 -> 2 -> 6 -> 7 -> 9'
var assert = require('assert');
​
function mergeSortedLists(head1, head2) {
// fill in this method
return head;
}
​
// Supporting data structures
​
function Node(val) {
this.val = val;
this.next = null;
}
​
class LinkedList {
constructor() {
this.head = null;
this.tail = null;
}
​
prepend(newVal) {
const currentHead = this.head;
const newNode = new Node(newVal);
newNode.next = currentHead;
this.head = newNode;
​
if (!this.tail) {
this.tail = newNode;
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
Tired of reading? Watch this video explanation!
To change the speed of the video or see it in full screen, click the icons to the right of the progress bar.

We'll now take you through what you need to know.
How do I use this guide?
Access all course materials today
The rest of this tutorial's contents are only available for premium members. Please explore your options at the link below.