Merge Two Sorted Lists
Problem statement
Given the heads of two singly linked lists sorted in nondecreasing order, merge them into one sorted list by linking their existing nodes. Return its head and keep every value, including duplicates.
The input lists are acyclic and share no nodes. Each displayed array lists node values in order; [] means a null head.
Function
mergeTwoLists(list1: ListNode, list2: ListNode) → ListNodeExamples
Example 1
list1 = [0,3,8]list2 = [1,3,9]return = [0,1,3,3,8,9]Taking the smaller remaining head gives [0,1,3,3,8,9]. Both nodes with value three are retained.
Example 2
list1 = []list2 = [-2,5]return = [-2,5]The first list is empty, so the second list is the whole result: [-2,5].
Constraints
0 <= list1.length <= 2500 <= list2.length <= 250-1000000 <= list1[i] <= 1000000-1000000 <= list2[i] <= 1000000- Both lists are sorted in nondecreasing order.