Partition List

Medium#86dummy head

You get a linked list and a number x. Reorder the nodes so that all nodes with values under x come before the nodes with values x or more, and inside each group the nodes keep their order. Return the head. Our example: 6 → 1 → 9 → 4 → 2, x = 5 — the answer is 1 → 4 → 2 → 6 → 9.

input
head: the head of a linked list, maybe empty; x: an integer.
returns
The head of the list with every node less than x before every node greater than or equal to x; each part keeps its nodes in their original order.
constraints
  • 0 ≤ nodes ≤ 200
  • −100 ≤ Node.val ≤ 100
  • −200 ≤ x ≤ 200
our 12 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} x
 * @return {ListNode}
 */
function partition(head, x) {

}
Ctrl ↵
format
reset

saved in this browser

12 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more linked list pointers problems

Pattern “Linked list pointers” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.