☰ All problems

24. Merge Two Sorted Lists

EasyLinked ListRecursion

You are given the heads of two singly linked lists, list1 and list2, each sorted in non-decreasing order.

Combine them into one sorted list built by relinking the existing nodes (no need to allocate new ones), and return its head.

Example 1
Input: list1 = [1,4,6], list2 = [2,3,7]
Output: [1,2,3,4,6,7]
Example 2
Input: list1 = [], list2 = []
Output: []
Example 3
Input: list1 = [], list2 = [5]
Output: [5]

Explanation: When one list is empty, the answer is simply the other list.

Constraints

  • Each list has between 0 and 100 nodes
  • -200 <= Node.val <= 200
  • Both lists are sorted in non-decreasing order
💡 Hint 1

At every step the next node of the result is the smaller of the two current heads.

💡 Hint 2

A dummy (sentinel) node in front of the result saves you from special-casing the first node.

💡 Hint 3

Once one list runs out, attach the rest of the other list in one step.

/**
 * Definition for singly-linked list (provided):
 * function ListNode(val, next) { this.val = val ?? 0; this.next = next ?? null; }
 *
 * @param {ListNode} list1
 * @param {ListNode} list2
 * @return {ListNode}
 */
function mergeTwoLists(list1, list2) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc