Sort List
Problem
Given the head
of a linked list, return the list after sorting it in ascending order.
Example 1:
Input: head = [4,2,1,3] Output: [1,2,3,4]
Example 2:
Input: head = [-1,5,3,4,0] Output: [-1,0,3,4,5]
Example 3:
Input: head = [] Output: []
Constraints:
- The number of nodes in the list is in the range
[0, 5 * 104]
. -105 <= Node.val <= 105
Solution
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var sortList = function(head) {
// list size 0 or 1
if (!head?.next) {
return head;
}
// split list into two
let slow = head;
let fast = head;
while (fast.next?.next) {
slow = slow.next;
fast = fast.next?.next;
}
let l1 = head;
let l2 = slow.next;
slow.next = null;
// divide and conquer
l1 = sortList(l1);
l2 = sortList(l2);
return merge(l1, l2);
};
var merge = function(l1, l2) {
const dummy = new ListNode();
let cur = dummy;
while (l1 && l2) {
if (l1.val < l2.val) {
cur.next = l1;
l1 = l1.next;
} else {
cur.next = l2;
l2 = l2.next;
}
cur = cur.next;
}
cur.next = l1 ?? l2;
return dummy.next;
};
We will implement a classic merge sort algorithm to sort the linked list head
.
Follow-up
Can you sort the linked list in O(n logn)
time and O(1)
memory (i.e. constant space)?
Solution
This is non-trivial, but is doable if we implement a bottom-up version of merge sort instead of top-down. This way, we no longer use recursion (ie. get rid of the additional space used to store the call stack).