- 要求:在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
- 解法:对链表进行快速排序
- code
/**
* 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) {
quicksort(head,NULL);
return head;
}
void quicksort(ListNode* head, ListNode* tail)
{
if(head == tail || head->next == NULL) return;
ListNode* p = Partion(head,tail);
quicksort(head,p);
quicksort(p->next,tail);
}
ListNode* Partion(ListNode* head, ListNode* tail)
{
int p = head->val;
ListNode* L = head;
ListNode* R = head->next;
while(R != NULL && R != tail)
{
if(R->val > p){
R = R->next;
}else{
L = L->next;
swap(L,R);
R = R->next;
}
}
swap(L,head);
return L;
}
void swap(ListNode* a, ListNode* b)
{
int tmp = a->val;
a->val = b->val;
b->val = tmp;
}
};