# 86. Partition List

## 1.問題&#x20;

* 給予一個linked list以及數字x, 分割list: 小於x的要放在大於等於x的node之前

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LNcivxVEXEeloBWtcTW%2F-LNcxjqDqagfpOU9TIyv%2F%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%202018-09-30%20%E4%B8%8B%E5%8D%881.32.28.png?alt=media\&token=eee6b8b4-fdad-44b2-98dd-83666ad67221)

## 2.想法 <a href="#id-2-xiang-fa" id="id-2-xiang-fa"></a>

* 提問
  * 確認題意:  將輸入的兩個字串轉為數字相乘並返回對應的字串
* function header, parameter
* test input
* 說明想法
  * Create 2 lists
    * list 1用來保留小於x的node
    * list 2用來儲存大於等於x的node
    * 最後將list2接到list 1後面
* 測試計算複雜度

## **3.程式碼** <a href="#id-3-cheng-shi" id="id-3-cheng-shi"></a>

```
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
        if (!head) {
            return NULL;
        }
        
        ListNode* tmp1 = new ListNode(0), *pre1 = tmp1;
        ListNode* tmp2 = new ListNode(0), *pre2 = tmp2; 
        ListNode* curr = head;
        while (curr) {
            if (curr->val < x) {
                pre1->next = curr;
                pre1 = pre1->next;
                curr = curr->next;
            } else {
                pre2->next = curr;
                curr = curr->next;
                pre2 = pre2->next;
                pre2->next = NULL;
            }
        }
        
        pre1->next = tmp2->next;
        
        return tmp1->next;
    }
};
```
