# 148. Sort List

## 1.問題

* 排序, 時間複雜度為O(n logn), 空間複雜度為constant

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LI-cZVNsvE32iLPvgZ0%2F-LI03z2UMfWNTTy3G8Cx%2F2018072210.jpg?alt=media\&token=5898ef55-d216-4d14-a509-f84216b4eac4)

## 2.想法&#x20;

* Divide and conquer, Binary sort
  * 將List分為前後兩段並排序

## 3.程式碼

```
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* sortList(ListNode* head) {
        if (!head || !head->next) {
            return head;
        }
        
        //Split the list
        ListNode* prev = NULL;
        ListNode* firstHalf = head;
        ListNode* secondHalf = head;
        while (secondHalf && secondHalf->next) {
            prev = firstHalf;
            firstHalf = firstHalf->next;
            secondHalf = secondHalf->next->next;
        }
        
        //The head of the scend half one
        ListNode* mid = firstHalf;
        prev->next = NULL;
        
        //Divid and conquer
        ListNode* l = sortList(head);
        ListNode* r = sortList(mid);
        
        //Combine
        return mergeList(l, r);
    }
private: 
    ListNode* mergeList(ListNode* l1, ListNode* l2){
        ListNode* newNode = new ListNode(0);
        ListNode* curr = newNode;
        //traversal 2 list at the same time
        while (l1 && l2) {
            if (l1->val <= l2->val) {
                curr->next = l1;
                //move
                l1 = l1->next;
            } else {
                curr->next = l2;
                //move
                l2 = l2->next;
            }
            //move
            curr = curr->next;
        }
        
        //attach remained list
        if (l1) {
            curr->next = l1; 
        }
        if (l2) {
            curr->next = l2; 
        }
        return newNode->next;
    }
};
```

## 4.Performance

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LI-cZVNsvE32iLPvgZ0%2F-LI040fwQ73cDBQihnCb%2F2018072211.jpg?alt=media\&token=59b3b30d-5d45-4839-9463-2db426cda035)
