# Problem 86: Partition List

> <https://leetcode.com/problems/partition-list/>

**类比**: Partion Array 这道题

> <http://www.lintcode.com/en/problem/partition-array/>

## 思路

* 创建一个left LinkedList，一个right LinkedList。
* 遇到小的挂left上，遇到大的挂right上
* 最后合并 left 和 right

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

        ListNode leftDummy = new ListNode(0);
        ListNode rightDummy = new ListNode(0);
        ListNode left = leftDummy;
        ListNode right = rightDummy;

        while (head != null) {
            if (head.val < x) {
                left.next = head;
                left = head;
            } else {
                right.next = head;
                right = head;
            }
            head = head.next;
        }

        right.next = null;
        left.next = rightDummy.next;

        return leftDummy.next;
    }
}
```

## 易错点

1. 两个指针，left用来探路，leftDummy用来标记“头”

   ```java
   ListNode left = leftDummy;
   ListNode right = rightDummy;
   ```
2. LinkedList的循环

   ```java
   while (head != null) {
    执行语句;
    head = head.next;
   }
   ```

   其中，`head = head.next;`作为增加变量使用的。
3. 掐头去尾进行拼接

   ```java
   right.next = null;
   left.next = rightDummy.next;
   ```


---

# 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://liuyang89116.gitbook.io/my-leetcode-book/chapter_4_linked_list/reverse-linked-list/problem_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.
