Merge Two Sorted Linked Lists
Problem statement
Given the heads of two disjoint singly linked lists sorted in nondecreasing order, merge them into one sorted linked list and return its head.
Relink the existing data nodes rather than copying their values into newly allocated data nodes. A temporary sentinel node is allowed. Preserve every duplicate. When equal heads are available, take the node from first before the node from second.
Each displayed list is its sequence of node values. An empty list represents a null head. Inputs contain no cycles or shared nodes.
Function
mergeSortedLists(first: ListNode, second: ListNode) → ListNodeExamples
Example 1
first = [1,2,4]second = [1,3,4]return = [1,1,2,3,4,4]Each original node appears once in sorted order, including both ones and both fours.
Example 2
first = []second = [0]return = [0]An empty first list leaves the second list unchanged.
Constraints
- Each list contains between
0and10000nodes. -10^9 <= node.val <= 10^9.