题目:Sort a linked list in O(nlogn)time using constant space complexity.
题解:本来想用快排来做,但是看了网上博客说,在快排的最坏情况下是O(n平方),所以就用了归并排序。
</pre><pre code_snippet_id="653676" snippet_file_name="blog_20150426_3_5518759" name="code" class="html">class Solution {
private:
ListNode *getMid(ListNode *head){ //找到中间位置
if(!head) return NULL;
if(!(head->next)) return head;
ListNode *slow,*fast;
slow = head;
fast = head->next;
while(fast&&fast->next)
{
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
ListNode *MemeryArray(ListNode *l1,ListNode *l2) //合并两个链表
{
if(!l1) return l2;
if(!l2) return l1;
ListNode *merge=new ListNode(0);
ListNode *head = NULL;
head = merge;
while(l1&&l2){
ListNode *node = new ListNode(0);
if(l1->val >l2->val)
{
node->val = l2->val;
l2 = l2->next;
}else{
node->val = l1->val;
l1 = l1->next;
}
merge->next = node;
merge = merge->next;
}
if(l1){
merge->next = l1;
merge = merge->next;
}
if(l2){
merge->next = l2;
merge = merge->next;
}
head = head->next;
return head;
}
public:
ListNode *sortList(ListNode *head) {
if(!head) return NULL;
if(!head->next) return head;
ListNode *nextpart = new ListNode(0);
ListNode *mid = getMid(head);
if(mid)
{
nextpart = mid->next;
mid->next = NULL;
}
return MemeryArray(sortList(head),sortList(nextpart));
}
};