# 86     Partition List

## 86. [Partition List](https://leetcode.com/problems/partition-list/description/)

## 1. Question

Given a linked list and a valuex, partition it such that all nodes less thanxcome before nodes greater than or equal tox.

You should preserve the original relative order of the nodes in each of the two partitions.

For example,\
Given`1->4->3->2->5->2`andx= 3,\
return`1->2->2->4->3->5`.

## 2. Implementation

```java
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode partition(ListNode head, int x) {
        if (head == null || head.next == null) {
            return head;
        }

        ListNode less = new ListNode(0);
        ListNode equalOrMore = new ListNode(0);
        ListNode p1 = less;
        ListNode p2 = equalOrMore;

        ListNode curNode = head;

        while (curNode != null) {
            if (curNode.val < x) {
                p1.next = curNode;
                p1 = p1.next;
            }
            else {
                p2.next = curNode;
                p2 = p2.next;
            }
            curNode = curNode.next;
        }

        p2.next = null;
        p1.next = equalOrMore.next;
        return less.next;
    }
}
```

## 3. Time & Space Complexity

时间复杂度O(n), 空间复杂度O(1)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://protegejj.gitbook.io/oj-practices/chapter1/linked-list/86-partition-list.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
