Given the head of a singly linked list, return the head of the list sorted in ascending order. The input is a real ListNode chain built by the judge from a flat JSON array such as [4, 2, 1, 3], and whatever linked list you return is serialized back to the same flat-array form for grading.
You may solve this by collecting values into an array and rebuilding the list, but interviewers usually want the linked-list merge-sort solution because it keeps the sorting work on the nodes themselves.
Input / output
head: ListNodeListNode — the head of the sorted linked listExamples
head = [4, 2, 1, 3] returns [1, 2, 3, 4].head = [-1, 5, 3, 4, 0] returns [-1, 0, 3, 4, 5].head = [] returns [].Constraints
0 <= number of nodes <= 50,000-100,000 <= node value <= 100,000Follow-up
Can you sort the list in O(n log n) time without converting it to an array first, and explain why merge sort is a natural fit for linked lists?