EasyLinked ListRecursion

Merge Two Sorted Lists

LeetCode
1 approach, code in all languages

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.
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now