Table of Contents
To merge two sorted singly linked lists, compare their first remaining nodes, append the smaller one, and advance the list it came from. When one list runs out, attach the other list’s remaining nodes. For example, 1 → 4 → 7 and 2 → 4 → 8 merge into 1 → 2 → 4 → 4 → 7 → 8.

Merge in place by reusing the nodes

class Node:
def __init__(self, value, next_node=None):
self.value = value
self.next = next_node
def merge_sorted(a, b):
sentinel = Node(None)
tail = sentinel
while a is not None and b is not None:
if a.value <= b.value:
tail.next = a
a = a.next
else:
tail.next = b
b = b.next
tail = tail.next
tail.next = a if a is not None else b
return sentinel.next
The sentinel makes the first insertion work like the rest. Each step appends the smallest value still available. Ties take a node from the first list before the second. The algorithm takes O(m + n) time and O(1) auxiliary space.
The input lists must be sorted in ascending order, acyclic, and disjoint. This version modifies their links. Calling code that needs both original lists should use a copy instead.
Build a merged copy if the originals must remain usable

One option is to collect the values, sort them, and build a fresh chain. You can avoid sorting by using the same two-pointer comparison and appending a new node with the selected value at each step. That takes O(m + n) time and allocates O(m + n) nodes. Mutable values are still shared if you copy only the node references to those values.
Test both lists empty, either list empty, duplicate values, and lists of different lengths. For more pointer practice, see how to reverse a singly linked list and the Stanford linked-list materials.
Reader Comments 0
Sign in with email or Google to join the discussion.