Typorithm · easy

Merge Two Sorted Lists

merge-two-sorted-listslinked-listsdummy-nodetail-pointersplice
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Merge Two Sorted Lists

0%

Linked Lists

Use a dummy head and a tail pointer, repeatedly splicing the smaller front node.

Merging two sorted lists reuses existing nodes instead of allocating new ones.

A dummy node lets you append uniformly without a special case for the first node.

When one list empties, the other's remaining (already sorted) nodes attach directly.

01

Dummy head simplifies the first append.

02

Splice the smaller front node.

03

Attach the leftover list at the end.

function mergeTwoLists(a, b) {
  const dummy = { val: 0, next: null };
  let tail = dummy;

  while (a !== null && b !== null) {
    if (a.val <= b.val) {
      tail.next = a;
      a = a.next;
    } else {
      tail.next = b;
      b = b.next;
    }

    tail = tail.next;
  }

  tail.next = a !== null ? a : b;
  return dummy.next;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Dummy head

A dummy node avoids special-casing the first append.

const dummy = { val: 0, next: null }

2. Pick smaller

Attach the smaller front node to keep order.

if (a.val <= b.val)

3. Splice in

Link the chosen node onto the merged tail.

tail.next = a

4. Advance tail

Move the tail to the node just appended.

tail = tail.next

5. Attach remainder

One list may still have sorted nodes — append them all.

tail.next = a !== null ? a : b

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Merge Two Sorted Lists: Lesson & Practice · Typorithm | ApplyDjinn