Practice · Linked list · 1 of 6

Merge Two Sorted Linked Lists

You are given list1 and list2, the heads of two singly linked lists (either may be empty). Each list's values are in non-decreasing order.

Join them into a single list whose values are in non-decreasing order, by relinking the nodes you were given rather than making new ones, and return its head.

Linked lists are written as their values from head to tail, so [1, 4, 6] is 1 → 4 → 6, and [] is an empty list.

Example 1

Input
list1 = [2, 5, 9], list2 = [1, 5, 6, 12]
Output
[1, 2, 5, 5, 6, 9, 12]

Example 2

Input
list1 = [], list2 = [3]
Output
[3]
Merging with an empty list leaves the other list as it is.

Constraints

  • Each list holds 0 to 5000 nodes.
  • Every value is between −10⁴ and 10⁴.
  • Each list is sorted in non-decreasing order.