1. Dummy head
A dummy node avoids special-casing the first append.
const dummy = { val: 0, next: null }Typorithm · easy
Step 1 of 8 · intro card
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.
Dummy head simplifies the first append.
Splice the smaller front node.
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;
}Connect each part of the code to the concept before you type.
A dummy node avoids special-casing the first append.
const dummy = { val: 0, next: null }Attach the smaller front node to keep order.
if (a.val <= b.val)Link the chosen node onto the merged tail.
tail.next = aMove the tail to the node just appended.
tail = tail.nextOne list may still have sorted nodes — append them all.
tail.next = a !== null ? a : bRead the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.