Skip to content

Instantly share code, notes, and snippets.

@lienista
Last active October 11, 2018 22:53
Show Gist options
  • Select an option

  • Save lienista/3b0dd1ea4260b5ecc2bf2e3abc4edfe5 to your computer and use it in GitHub Desktop.

Select an option

Save lienista/3b0dd1ea4260b5ecc2bf2e3abc4edfe5 to your computer and use it in GitHub Desktop.
Leetcode 86. Partition List - Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. You should preserve the original relative order of the nodes in each of the two partitions.
const partition = (head, x) => {
if(head === null) return head;
let beforeStart = null,
beforeEnd = null,
afterStart = null,
afterEnd = null;
while(head) {
let next = head.next;
head.next = null;
if(head.val < x) {
if(!beforeStart) {
beforeStart = head;
beforeEnd = beforeStart;
} else {
beforeEnd.next = head;
beforeEnd = head;
}
} else {
if(!afterStart) {
afterStart = head;
afterEnd = afterStart;
} else {
afterEnd.next = head;
afterEnd = head;
}
}
head = next;
}
if(!beforeStart) {
return afterStart;
}
beforeEnd.next = afterStart;
return beforeStart;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment