Merge Lists

Merge Lists

Merge two sorted (ascending) linked lists into one sorted list, and return its head. Reuse the existing nodes.

mergeLists(a, b)

Input format: listA | listB — each already sorted ascending. Output the merged list, space-separated.

Examples

(1 → 3 → 5) , (2 → 4 → 6)   // → 1 → 2 → 3 → 4 → 5 → 6
(1 → 2) , (3 → 4)            // → 1 → 2 → 3 → 4
(empty) , (1 → 2)            // → 1 → 2

Walkthrough

Thinking it through

This looks similar to zippering two lists, but the rule for picking the next node differs: instead of blindly alternating, you pick whichever list currently has the smaller front value. Doing this correctly is what makes the result come out fully sorted.

Why comparing the fronts is enough

Both lists are already sorted ascending, so the smallest remaining value in either one always sits right at its front — everything after the front is equal or larger. That means the smallest value not yet placed in the output must be one of the two front values you're looking at right now. A single comparison between the two fronts is always enough to know which one belongs next.

Building the approach

Use the same dummy-head-and-tail scaffolding as any "build a new list by appending" problem. Then:

  1. While both lists still have nodes, compare their front values.
  2. Attach the smaller one (either, if equal) to the result, and advance that list's pointer.
  3. Move the tail pointer to the node you just attached.
  4. Repeat until one list runs out.

Why the leftover step is safe

Once one list is exhausted, everything already placed in the result is less than or equal to everything remaining in the other list — because you always chose the smaller front at each step. So there's no need to keep comparing one at a time; splice the entire remaining chunk of the non-empty list directly onto the tail, and the result stays sorted.

Why this is optimal

Each node from either list is visited and relinked exactly once, so total work is proportional to their combined length — you can't merge two sorted sequences faster than looking at every element once. And since you reuse the original nodes, no extra memory is needed beyond a handful of pointers.

Contrast with zippering

Zipper alternates sources unconditionally; this problem picks a source based on comparison. That's the key difference, even though the surrounding dummy-head/tail machinery is identical.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.