Letcode 148 Sort List Python 3 Solution
Approach - We use a merge sort for solving this problem it has to be done in O(N log N) and constant space O(1). We use the idea of merge sort where we first divide the list into two halves, doing so in an Array is easy but in a linked list, you have to do something different. We use the concept of fast and slow pointers where fast pointer traverses directly at a gap of two nodes whereas slow pointer traverses one at a time. so when our fast pointer reaches the end of the Linked list, our slow pointer will be pointing at the middle element of the linked list. We also take a temp variable which will store the slow pointer before its increment so that we can make it null which will be our end node of the first list. You can better understand by looking at the code below.
|
|