---
# System prepended metadata

title: 'LeetCode #148 [Sort List](https://leetcode.com/problems/sort-list/)'
tags: [LeetCode, Medium, Linked List]

---

###### tags: `LeetCode` `Linked List` `Medium`
# LeetCode #148 [Sort List](https://leetcode.com/problems/sort-list/)
### (Medium)

給你鏈結串列的頭結點 head，請將其按 升序 排列並返回排序後的鏈結串列。

![](https://i.imgur.com/g83KneM.png)


---
將所有元素放入數組中排列, 再還原成鏈結串列。

---
```
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* sortList(ListNode* head) {
        vector<int> store;
        while(head){
            store.push_back(head->val);
            head = head->next;
        }
        sort(store.begin(), store.end());
        ListNode *ans=nullptr, *tmp=nullptr, *prev=nullptr;
        for(auto i:store){
            tmp = new ListNode(i);
            if(!prev)ans = tmp;
            else prev->next = tmp;
            prev = tmp;
        }
        return ans;
    }
};
```