# 143. Reorder List

## 1.問題

* **給予一個linked list, 重新排序**

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LNZFcp09zs3Rg5-R4eR%2F-LNZTygBDrCw_oWWHpYS%2F%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%202018-09-29%20%E4%B8%8B%E5%8D%884.39.35.png?alt=media\&token=be9d4b59-dfd4-46e3-9247-aa961b17d14f)

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

* 提問
* function header, parameter
* test input
* 觀察
* 說明想法
  * 這類題目看起來很複雜, 重點是要仔細分析後熟悉linked list的運算
    * 將list平分成兩段
    * 將list 2逆轉
    * 將list 2依序插入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:
    void reorderList(ListNode* head) {
        if (!head) {
            return;
        }
        
        //Find middle point
        ListNode* slow = head;
        ListNode* fast = head;
        while (fast->next && fast->next->next) {
            slow = slow->next;
            fast = fast->next->next;
        }
        
        ListNode* mid = slow->next;
        slow->next = NULL;
        
        //Reverse second part
        ListNode* last = mid, *pre = NULL;
        while (last) {
            ListNode *next = last->next;
            last->next = pre;
            pre = last;
            last = next;
        }
        
        //Inset the second list into first list
        while (head && pre) {
            ListNode *next = head->next;
            head->next = pre;
            pre = pre->next;
            head->next->next = next;
            head = next;
        }
        
    }
};
```
