class Solution{
public:
ListNode* sortList(ListNode* head)
{
if(head == NULL || head->next == NULL)
return head;
ListNode* begin = head, *end = NULL;
Quicksort_list(begin, end);
return begin;
}
void Quicksort_list(ListNode* begin, ListNode* end)
{
ListNode* curnode = NULL;
if(begin != end)
{
curnode = partition(begin, end);
Quicksort_list(begin, curnode);
Quicksort_list(curnode->next, end);
}
}
ListNode* partition(ListNode* begin, ListNode* end)
{
int key = begin->val;
ListNode* p = begin, * q = p->next;
while(q)
{
if(q->val < key) //精髓
{
p = p->next;
swap(p->val, q->val);
}
q = q->next;
}
swap(begin->val, p->val);
return p;
}
void scanList(ListNode* head)
{
while(head != NULL)
{
cout<<head->val;
if(head->next != NULL)
cout<<"->";
head = head->next;
}
}
};
链表快排
最新推荐文章于 2022-10-22 17:58:18 发布