Skip to content

Instantly share code, notes, and snippets.

@RP-3
Created August 20, 2020 22:56
Show Gist options
  • Select an option

  • Save RP-3/def6160ee6026c7e6e1d28c128446c5e to your computer and use it in GitHub Desktop.

Select an option

Save RP-3/def6160ee6026c7e6e1d28c128446c5e to your computer and use it in GitHub Desktop.
// O(n) time, O(1) space
var reorderList = function(head) {
if(!head || !head.next) return;
// split in half
let [slow, fast, prev] = [head, head, null];
while(fast && fast.next){
prev = slow;
slow = slow.next;
fast = fast.next.next;
}
let backHalfHead = prev.next;
prev.next = null;
// reverse second half
let [a, b] = [backHalfHead, backHalfHead.next];
a.next = null;
while(b){
let tmp = b.next;
b.next = a;
a = b;
b = tmp;
}
backHalfHead = a;
// weave together
[a, b] = [head, backHalfHead];
while(a && b){
let tmpA = a.next;
let tmpB = b.next;
a.next = b;
b.next = tmpA || tmpB;
a = tmpA;
b = tmpB;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment