Merge Two Sorted Lists

EasyLinked lists

You get the heads of two singly linked lists, list1 and list2, each sorted from smallest to largest. Join them into one sorted list made of their nodes, and return its head.

Each node has a val and a next pointer. On this page a list is written as an array of its values, from head to tail, and [] is an empty list.

Examples

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

The fronts are compared one pair at a time, and both 5s are kept.

Example 2
Input:  list1 = [], list2 = [3, 4]
Output: [3, 4]

One list is empty, so the answer is the other one.

Constraints

  • Each list has 0 to 50 nodes.
  • -100 ≤ node.val ≤ 100
  • Both lists are sorted in non-decreasing order.

Stuck?

Hint 1

The smallest value left is always at the front of one of the two lists. Take it, and repeat.

Hint 2

Start from a dummy node so the first pick is not a special case. When one list runs out, link the rest of the other one on in one step.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 9 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur