Merge Two Sorted Lists
Problem statement
Given the heads of two singly linked lists, list1 and list2, return the head of one list containing all their values in nondecreasing order.
Each input list is already in nondecreasing order. Keep every occurrence of a repeated value. You may reuse input nodes or create new nodes; the returned value sequence is what matters.
An empty list is represented by []. If both lists are empty, return an empty list.
Function
mergeTwoLists(list1: ListNode, list2: ListNode) → ListNodeExamples
Example 1
list1 = [1,3,5]list2 = [1,2,6]return = [1,1,2,3,5,6]The values from both lists in sorted order are [1, 1, 2, 3, 5, 6]. Both occurrences of 1 are kept.
Example 2
list1 = []list2 = [-2,0]return = [-2,0]The first list is empty, so all values come from the second list in their existing order.
Constraints
- Each list contains between
0and5000nodes. - Each node value is between
-10000and10000, inclusive. - Both lists are acyclic, are disjoint, and are in nondecreasing order.