TRT
Sign in
easyFoundationsLeetCode#dummy head#merge

Merge two sorted lists

Splice the nodes of two sorted linked lists into one sorted list, using a dummy head and a tail pointer.

The Runtime Theory Team1 min read
Taught inInsert, delete and the dummy headInserting or deleting in a linked list is a couple of pointer writes, if you hold the node before the change. A dummy head node removes the special case of changing the first node.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inlist1 = [1, 2, 4], list2 = [1, 3, 4]

out[1, 1, 2, 3, 4, 4]

inlist1 = [], list2 = []

out[]

inlist1 = [], list2 = [0]

out[0]

Given the heads of two sorted linked lists, merge them into one sorted list made by splicing together the existing nodes, and return its head.

Before you code

Without a dummy head, the first node of the result is a special case: you have to decide which list it comes from before the loop. With one, the loop is the same from the first node to the last.

Hints

  1. Create dummy and set tail = dummy.
  2. While both lists have nodes, attach the smaller head to tail.next, advance that list, and advance tail.
  3. When one list runs out, attach the rest of the other in one step: tail.next = l1 or l2.
  4. Return dummy.next. No new nodes are created apart from the dummy.

Production & complexity notes

When solving Merge two sorted lists on LeetCode (easy), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Insert, delete and the dummy head to reinforce the underlying pattern.

What it practices

The dummy head and pointer splicing, from Insert, delete and the dummy head.

Not started

Sign in to save your learning progress.

Sign in to save