148. Sort List
Medium
Problem:
Sort the linked list in O(nlogn) time complexity.

https://leetcode.com/problems/sort-list
Solution:
Merge Sort
Due to its nature, it's difficult to arbitrarily designate a pivot in a linked list, so a fixed position must be chosen.
For the divide-and-conquer strategy of merge sort, the list should be split in the middle. However, since the total length of a linked list is unknown, we need to employ the Runner technique.
Using three variables,
half,slow, andfast, moveslowone step at a time andfasttwo steps at a time. Whenfastreaches the end,slowwill be in the middle. At this point, sethalfto the value right beforeslowand cut off the linked list relationship based on the position ofhalf.Finally, compare the sizes of the divided items and merge them back together in a sorted manner.
A practical method using built-in functions
If you need to write algorithms on a whiteboard during an interview, you should avoid this approach.
Last updated