Partition List
Given a linked list and a value x, partition it so all nodes < x come before nodes >= x.
Example: head = [1,4,3,2,5,2], x = 3 → [1,2,2,4,3,5]
Sample Input
—
Sample Output
—
Constraints
- 0 to 200 nodes
- -100 <= Node.val <= 100
- -200 <= x <= 200
Topics
Two Lists
function partition(head, x) {
const before = {next:null}, after = {next:null};
let b = before, a = after;
while (head) {
if (head.val < x) { b.next = head; b = b.next; }
else { a.next = head; a = a.next; }
head = head.next;
}
a.next = null; b.next = after.next;
return before.next;
}
Time: O(n) | Space: O(1)
Saved in this browser only. Private to you.