Skip to content

Instantly share code, notes, and snippets.

@RP-3
Created April 10, 2020 04:00
Show Gist options
  • Save RP-3/283061df0b54d6e4eedd450cb64e39b0 to your computer and use it in GitHub Desktop.
Save RP-3/283061df0b54d6e4eedd450cb64e39b0 to your computer and use it in GitHub Desktop.
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var sortList = function(head) {
if(!head || !head.next) return head;
// now any list is of size > 1
const midNode = midPointNode(head); // TBI. Returns the middle node in the list
const right = midNode.next;
midNode.next = null;
const leftSorted = sortList(head);
const rightSorted = sortList(right);
// leftSorted and rightSorted are now guaranteed size 0 or 1
return merge(leftSorted, rightSorted);
};
// private helpers
const merge = (a, b) => {
let head, aCurr, bCurr;
if(a.val < b.val){
head = a;
aCurr = a.next;
bCurr = b;
}else{
head = b;
aCurr = a;
bCurr = b.next;
}
let listCurr = head;
while(aCurr || bCurr){
if(!aCurr){ // append b
listCurr.next = bCurr;
listCurr = listCurr.next;
bCurr = bCurr.next;
}
else if(!bCurr){ // append a
listCurr.next = aCurr;
listCurr = listCurr.next;
aCurr = aCurr.next;
}
else if(aCurr.val < bCurr.val){ // append a
listCurr.next = aCurr;
listCurr = listCurr.next;
aCurr = aCurr.next;
}
else{ // append b
listCurr.next = bCurr;
listCurr = listCurr.next;
bCurr = bCurr.next;
}
}
return head;
};
const midPointNode = (node) => {
let [slow, fast] = [node, node.next];
while(fast.next && fast.next.next){
slow = slow.next;
fast = fast.next.next;
}
return slow;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment