您的位置:首页 > 其它

Leetcode # 148 Sort List

2015-07-31 22:24 267 查看
Sort a linked list in O(n log n)
time using constant space complexity.

Difficulty:Medium

借鉴之前的merge two sorted list,类似qsort的方法排序.

</pre><pre name="code" class="cpp">ListNode* getMid(ListNode* curr)
{
ListNode* p = curr;
ListNode* p1 = curr;
while(p1->next!=NULL&&p1->next->next!=NULL)
{
p = p->next;
p1 = p1->next->next;
}
return p;
}

ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(l1==NULL)
return l2;
if(l2==NULL)
return l1;
ListNode* p=NULL;

if(l1->val>=l2->val){
p = l2;
p->next = mergeTwoLists(l2->next,l1);
}

if(l2->val>l1->val){
p = l1;
p->next = mergeTwoLists(l1->next,l2);
}

return p;

}

ListNode* sortList(ListNode* head) {
if(head==NULL||head->next==NULL)
return head;
ListNode* mid = getMid(head);
ListNode* next = mid->next;
mid->next = NULL;
return mergeTwoLists(sortList(head),sortList(next));

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: