Partition List
Implement partition
Given the head of a linked list and a value x, rearrange the nodes so every node with a value less than x comes before every node with a value of x or more — preserving each group's original relative order — and return the new head. No node's value changes, and the split doesn't need to place x itself in any particular spot beyond "not less than x".
Growing two separate chains while walking the list once handles this directly: every node gets appended to whichever chain it belongs in, becoming that chain's new tail. A dummy node anchoring each chain means the very first node appended works exactly the same way as every later one — no special case for "is this the first node in this group?" Once every node has been placed, joining the less chain's tail to the geq chain's head produces the final list in one splice.
Example 1:
Input: head = [5,9,2,8,1,6], x = 5
Output: [2,1,5,9,8,6]
Example 2:
Input: head = [3,1], x = 2
Output: [1,3]
Example 3:
Input: head = [4], x = 4
Output: [4]
+ 5 hidden test cases run on Submit.
Constraints:
- ●
0 ≤ number of nodes in head ≤ 200 - ●
-1000 ≤ node value, x ≤ 1000
head =
[5, 9, 2, 8, 1, 6]
x =
5