Sort a linked list in O(n log n) time using constant space complexity.
比较蛋疼,我取巧了。可能不合题意。
/**
* 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) {
ListNode *p = head;
while(p)
{
list.push_back(p->val);
p = p->next;
}
sort(list.begin(), list.end());
head = build_list(list);
return head;
}
ListNode *build_list(vector<int> list)
{
ListNode *head = nullptr, *p = nullptr;
for(int i = 0; i < list.size(); i++)
{
ListNode *tmp = new ListNode(list[i]);
if(i == 0)
{
head = p = tmp;
continue;
}
p->next = tmp;
p = tmp;
}
return head;
}
private:
vector<int> list;
};