Merge a Pair of Ascending Linked Lists Recursively

Implement mergeTwoSortedListsRecursive

Given two sorted linked lists list1 and list2, merge them into a single sorted linked list by splicing the existing nodes together — no new nodes should be created. The recursive framing turns the merge into a chain of small decisions: compare the two current heads, let the smaller one lead, and set its `next` pointer to the result of recursively merging everything after it with the other list untouched. The base cases are immediate — merging anything with an empty list is just that list, unchanged. Every call makes exactly one decision and hands off a strictly smaller version of the same problem, so the total number of calls (and the total work) is proportional to the combined length of both lists — the same O(n+m) as the iterative two-pointer approach, just paying for it in call-stack frames instead of a fixed pair of pointers.

Example 1:

Input: list1 = [2,6,9], list2 = [1,6,8,12]

Output: [1,2,6,6,8,9,12]

Example 2:

Input: list1 = [], list2 = [5,7]

Output: [5,7]

Example 3:

Input: list1 = [3], list2 = []

Output: [3]

+ 2 hidden test cases run on Submit.

Constraints:

  • 0 ≤ number of nodes in list1, list2 ≤ 10 each
  • -100 ≤ node value ≤ 100
  • Both list1 and list2 are sorted in non-decreasing order

list1 =

[2, 6, 9]

list2 =

[1, 6, 8, 12]