Sort a linked list in O(n log n) time using constant space complexity.
O(nlogn)的有快速排序,归并排序,堆排序。这里需要采用归并排序。把一个链表分为等长的两个链表,对这两个链表分别进行归并排序,再将这两个链表有序合并。
class Solution { public: ListNode *sortList(ListNode *head) { if(head==NULL)return NULL; ListNode *p,*q,*hd=NULL,*temp=NULL; int n,l; n=0; p=head; while(p){ n++; p=p->next; } if(n==1)return head; l=n/2;p=head; for(int i=1;i<=l;i++){ if(i==l)temp=p; p=p->next; } temp->next=NULL; q=head; q=sortList(q); p=sortList(p); while(p&&q){ if(p->val<=q->val){ if(hd==NULL){ hd=temp=p; }else{ hd->next=p; hd=hd->next; } p=p->next; }else{ if(hd==NULL){ hd=temp=q; }else{ hd->next=q; hd=hd->next; } q=q->next; } } if(p)hd->next=p; if(q)hd->next=q; return temp; } };