###### tags: `LeetCode` `Linked List` `Medium` # LeetCode #148 [Sort List](https://leetcode.com/problems/sort-list/) ### (Medium) 給你鏈結串列的頭結點 head,請將其按 升序 排列並返回排序後的鏈結串列。  --- 將所有元素放入數組中排列, 再還原成鏈結串列。 --- ``` /** * 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; } }; ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up