Sort a linked list in O(n log n) time using constant space complexity.
排序一个链表可以类似于插入排序那样,这样需要每次都从头开始遍历找到插入位置,所以复杂度是O(n^2),所以这样是不行的,数组中的排序方法里快排和堆排并不适合。如果有两个排序的链表,将他们进行融合是很容易的,所以采用分治法,是可以很快求解的。所以答案如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* merge(ListNode* l1,ListNode *l2){
ListNode dummy(-1);
ListNode* p = &dummy;
while(l1&&l2){
if(l1->val < l2->val){
p->next = l1;
l1 = l1->next;
}
else{
p->next = l2;
l2 = l2->next;
}
p = p->next;
}
if(l1) p->next = l1;
if(l2) p->next = l2;
return dummy.next;
}
ListNode* sortList(ListNode* head) {
if(!head || !head->next) return head;
ListNode* slow = head, *fast = head;
while(fast->next&&fast->next->next){
slow = slow->next;
fast = fast->next->next;
}
ListNode *head2 = sortList(slow->next);
slow->next = NULL;
return merge(sortList(head),head2);
}
};