Merge Sorted Lists Visualizer
Linked ListEasyTwo pointers

Merge Sorted Lists Visualizer

Keep a tail on the result. Always attach the smaller of the two current heads, then advance that list.

In easy words

Like merging two sorted queues into one line: whoever has the smaller ticket goes next.

Where this shows up

Merge step of merge-sort, combining calendars, and k-list merge (with a heap).

Key facts

  • Dummy node - avoids a special case for the first real node.
  • Compare heads - attach the smaller one.
  • Advance - only that list moves.
  • Remainder - splice the leftover list at the end.

What to remember

  • Time - O(n + m).
  • Space - O(1) extra if you reuse nodes.
  • Stable - take from l1 when values are equal.
  • Empty list - result is the other list.

Theory

Because both lists are already sorted, the next global minimum is always one of the two heads. Reusing existing nodes means you only retarget pointers.

Problem Statement

Merge two sorted linked lists and return the head of the merged list.

Example: 1 → 3 → 5 and 2 → 4 → 6 become 1 → 2 → 3 → 4 → 5 → 6.

Approach

  1. Dummy head so you never special-case the first node. A tail pointer builds the merged list.
  2. Compare heads of A and B. Attach the smaller node to tail, then advance that list.
  3. Repeat until one list is empty, then splice the leftover chain in one shot.
  4. Return dummy.next. Both inputs are already sorted, so one pass is enough: O(n + m) time, O(1) extra space.

Visualization and algorithm execution

Ready

Example code

1dummy = Node(0)
2tail = dummy
3while l1 and l2:
4if l1.val <= l2.val:
5tail.next = l1; l1 = l1.next
6else:
7tail.next = l2; l2 = l2.next
8tail = tail.next
9tail.next = l1 or l2
Trace log

Step-by-step visualization

l1
l2
merged
Output:

Example program

Python

1def mergeTwoLists(l1, l2):
2dummy = ListNode(0)
3tail = dummy
4while l1 and l2:
5if l1.val <= l2.val:
6 tail.next = l1; l1 = l1.next
7else:
8 tail.next = l2; l2 = l2.next
9tail = tail.next
10tail.next = l1 or l2
11return dummy.next