Problem
Sort a linked list in O(n log n) time using constant space complexity.
Example 1:
1 |
|
Example 2:
1 |
|
Explanation
-
We can use merge sort method to solve this problem. We want to split the list, first define slow, fast, and pre pointer. The pre poitner is used for pointing at the previous position of the slow pointer. All three pointers initialized to the head.
-
Find the middle of the element in the list by using slow and fast pointer technique. If the list is 1->2->3->4, then slow is at node 3, pre is at node 2. We want to split the original list to 1->2 and 3->4, so we make
pre.next = null
. When there’s one node in the list, we return that node. -
After splitting, for the merge function taking
left
list andright
list as parameters, if left’s value is smaller, thenleft.next
is equal to the merge function of takingleft.next
andright
; similar for right’s value is greater or equal to left’s value. The base case is when either ofleft
orright
is null, we return anohter list.
Solution
1 |
|