Combine Two Sorted Linked ListsLoading saved progress…

Combine Two Sorted Linked Lists

You're given the heads of two singly linked lists, each already sorted in ascending order. Implement linkedListCombineTwoSorted(a, b) so it weaves them into a single ascending-sorted list and returns its head. Each node is a plain object of the shape { val, next }, where next points at the following node or is null at the end of the list. This is the classic merge step that sits at the heart of merge sort — given two sorted runs, produce one.

Signature

// A node is a plain object: { val: number, next: Node | null }.
// a, b: Node | null   — the heads of two ascending-sorted lists (null = empty).
// returns: Node | null — the head of one ascending-sorted list (null if both empty).
function linkedListCombineTwoSorted(a, b): Node | null;

Examples

// a: 1 -> 3 -> 5,  b: 2 -> 4 -> 6  (shown as arrays for brevity)
linkedListCombineTwoSorted(list([1, 3, 5]), list([2, 4, 6]));
// → 1 -> 2 -> 3 -> 4 -> 5 -> 6
// Duplicate values across both lists are all kept.
linkedListCombineTwoSorted(list([1, 1, 2]), list([1, 3]));
// → 1 -> 1 -> 1 -> 2 -> 3

Notes

  • Node shape. Every node is { val, next }. The list ends when a node's next is null. There is no separate ListNode class — just these plain objects.
  • Inputs are already sorted. Both a and b arrive in ascending order. Lean on that — you do not need to sort anything from scratch.
  • Splice, don't rebuild. Re-link the existing nodes into the merged order rather than allocating a fresh node per value. The only new node you should need is a single dummy head.
  • Empty inputs. Either head may be null. If one is empty, return the other; if both are empty, return null.
  • Don't mutate values. You may rewrite next pointers to splice nodes together, but leave each node's val alone.
Loading editor…