Sorta linked list in O(n log n)time using constant space complexity.
用O(nlogn)复杂度对链表进行排序,可以采用归并排序。那么需要对链表做如下操作:
(1)将链表从中点划分为2个链表。
(2)对左链表递归的进行归并排序
(3)对右链表递归的进行归并排序
(4)合并2个链表。
举个例子:
假如有一个链表为:4->6->5->7->2->3->null
则一分为2为:(1)4->6->5->null (2)7->2->3->null
由于是个递归的过程,那么会一直划分。先递归的划分(1)左链表得到:
1)4->6->null和5->null
2)4->null和6->null。
递归到此结束,然后将4和6合并得4->6->null。再和5->null合并得到4->5->6->null。至此归并左链表排序完成。
现在递归的划分(2)右链表得到:
1)7->2->null和3->null
2)7->null和2->null
再进行合并并逆过程,得到2->7->null。再和3->null合并得到2->3->7>null。
至此,左右两个链表(4->5->6->null和2->3->7>null)都归并排序完成,合并最终的左右链表得到2->3->4->5->6->7->null。
代码如下:
ListNode *sortList(ListNode *head) {
if(!head || !head->next)
return head;
ListNode *pre = head;
ListNode *after = head->next;
while(after && after->next)
{
pre = pre->next;
after = after->next->next;
}
ListNode *right = pre->next;
pre->next = NULL;
ListNode *l = sortList(head);
ListNode *r = sortList(right);
return Merge(l,r);
}
ListNode * Merge(ListNode *left,ListNode *right)
{
if(!left)
return right;
if(!right)
return left;
ListNode *head = NULL;
if(left->val < right->val)
{
head = left;
head->next = Merge(left->next,right);
}
else if(left->val >= right->val)
{
head = right;
head->next = Merge(left,right->next);
}
return head;
}