0148. Sort List
Medium | Linked List + MergeSort | 172 ms (98.38%), 45.6 MB (95.85%)
Source: LeetCode - Sort List GitHub: Solution / Performance
Given the head
of a linked list, return the list after sorting it in ascending order.
Follow up: Can you sort the linked list in O(n logn)
time and O(1)
memory (i.e. constant space)?
To meet O(1) memory complexity, we need to do Merge Sort by splitting the linked list into multiple segments bottom-up.
Before splitting, we need to get the length of the input linked list.
Then split the linked list bottom-up by starting with size = 1
, this size will grow two times of itself in each iteration by size *= 2
until size >= length
.
For the process of splitting and merging, we need to maintain two pointers:
splitHead is to check whether the splitting process needs to end or not.
mergeHead is for merging two split linked lists so that we can maintain relative order for the next splitting process.
Last updated