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:
1class Node:
2 def __init__(self, val):
3 self.value = val
4 self.next = None
5
6list1 = Node(1)
7list1.next = Node(2)
8
9print(list1.value, '->', list1.next.value)
Write a method called mergeSortedLists
that would be invoked as such in the following example:
1# List 1: list1 = [1, 5, 6]
2# List 2: list2 = [2, 3, 4]
3
4merged_list = merge_sorted_lists(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
55
​
def merge_sorted_lists(head1, head2):
# fill in
return head1
​
​
# Node definition
class Node:
def __init__(self, val):
self.val = val
self.next = None
​
​
def create_nodes(head, nodes):
for val in nodes:
new_node = Node(val)
head.next = new_node
head = new_node
​
​
list1 = Node(3)
nodes1 = [4, 5, 6, 7, 8, 9, 10]
create_nodes(list1, nodes1)
​
list2 = Node(1)
nodes2 = [2, 3, 4, 5, 6, 7, 8]
create_nodes(list2, nodes2)
​
​
def list_to_str(head):
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
Here's a video of us explaining the solution.
To change the speed of the video or see it in full screen, click the icons to the right of the progress bar.

Here's how we would solve this problem...
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.