您的位置:首页 > 其它

Leetcode156: Sort List

2015-11-13 16:05 330 查看
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) {
if(!head||!head->next)
return head;
return mergeSort(head);
}
ListNode * mergeSort(ListNode *head){
if(!head||!head->next)
return head;
ListNode *p=head, *q=head, *pre=NULL;
while(q&&q->next!=NULL){
q=q->next->next;
pre=p;
p=p->next;
}
pre->next=NULL;
ListNode *lhalf=mergeSort(head);
ListNode *rhalf=mergeSort(p);
return merge(lhalf, rhalf);
}
ListNode *merge(ListNode *a, ListNode *b)
{
ListNode *node = new ListNode(-1);
ListNode *ptr = node;
while(a && b)
{
if(a->val<=b->val)
{
ptr->next = a;
a = a->next;
}
else
{
ptr->next = b;
b = b->next;
}
ptr = ptr->next;
}
ptr->next = a!=NULL?a:b;
return node->next;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: