Merge Two Sorted Lists

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

Merge them into one sorted list by splicing their nodes together, without creating a new node for each value, and return the head of the merged list. Either list may be empty.

Constraints

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

Examples

Example 1

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

Taking the smaller head each time alternates between the two lists.

Example 2

Input: list1 = [], list2 = [0]
Output: [0]

One list is empty: the answer is the other list.

Example 3

Input: list1 = [1,1,2], list2 = [1,3]
Output: [1,1,1,2,3]

Ties can be taken from either list; the values come out as 1, 1, 1, 2, 3.

JavaScript you'll use: Linked list and tree nodes

/**
 * Linked list nodes are provided (you don't need to define them):
 * class ListNode { constructor(val = 0, next = null) { this.val = val; this.next = next; } }
 */
/**
 * @param {ListNode} list1
 * @param {ListNode} list2
 * @return {ListNode}
 */
function mergeTwoLists(list1, list2) {
  
}

Ctrl/⌘ + ' runs the examples, Ctrl/⌘ + Enter submits. Use console.log freely: output shows under Console. In the editor, press Esc then Tab to move focus out.