EasyLinked ListRecursion

1 approach, code in every language

Problem description

You are given the heads of two linked lists that are each sorted in non-decreasing order. Combine them into a single sorted list.

The merged list should be built by splicing together the existing nodes of the two inputs rather than by allocating new ones. Return the head of the resulting list.

Example 1

Input: list1 = [1,2,4], list2 = [1,3,4]

Output: [1,1,2,3,4,4]

Repeatedly picking the smaller front node from the two lists interleaves them into a single sorted chain.

Example 2

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

Output: [0]

When one list is empty there is nothing to compare, so the answer is simply the other list.

Constraints

  • The number of nodes in both lists is in the range [0, 50].
  • -100 <= Node.val <= 100
  • Both list1 and list2 are sorted in non-decreasing order.

After the pattern

Now solve one you haven't seen.

Splice Index Card Chains is our own problem on the technique behind Merge Two Sorted Lists: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free