Merge Two Sorted Lists

Easy Linked List AI round

list1 and list2 are the heads of two singly linked lists, and either may be empty. In each list the values never go down from the head to the tail.

Join them into one list whose values never go down either, holding every node of both lists once.

Return the head of the joined list, or null if both lists are empty.

Example 1

Input: list1 = [-6,2,2,15,40], list2 = [9,11]
Output: [-6,2,2,9,11,15,40]

-6 and both 2s come from list1 before list2 starts at 9. Then 9 and 11 go in before 15, list2 is used up, and the rest of list1, 15 and 40, ends the joined list.

Example 2

Input: list1 = [7,7], list2 = [2,7,9]
Output: [2,7,7,7,9]

Example 3

Input: list1 = [100], list2 = [-50,0,50]
Output: [-50,0,50,100]

Constraints

  • 0 ≤ number of nodes in each list ≤ 5 × 10⁴
  • -10⁹ ≤ node.val ≤ 10⁹
  • The values of each list never go down from its head to its tail

Watch the explanation

More Linked List

All Linked List problems