快排:
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
void swap(ListNode *l, ListNode *r)
{
int temp = l->val;
l->val = r->val;
r->val = temp;
}
ListNode *partion(ListNode *pstart, ListNode *pend)
{
int povit = pstart->val;
ListNode *left=pstart; //point to the less boundary
ListNode *right = pstart->next;
while (right != nullptr && right != pend->next)
{
if (right->val < povit)
{
left = left->next;
if(left!=right)
swap(left, right);
}
right = right->next;
}
swap(left, pstart);
return left;
}
void quick_sort(ListNode* pleft, ListNode* pright)
{
//注意此处的判断条件,因为可能partion到最后一个后,pos->next = nullptr
if (pleft == pright || pleft == nullptr)
return;
ListNode* pos = partion(pleft, pright);
quick_sort(pleft, pos);
quick_sort(pos->next, pright);
}
ListNode *sortList(ListNode *head) {
if (head == nullptr)
return head;
ListNode *endlist = head;
while (endlist->next != nullptr)
{
endlist = endlist->next;
}
quick_sort(head, endlist);
return head;
}
归并排序
//链表的归并排序
//合并两个排序链表
ListNode* MergeTwo(ListNode* pleft,ListNode* pright)
{
if (pleft == nullptr)
return pright;
if (pright == nullptr)
return pleft;
//确定头节点
ListNode* pHead = nullptr;
if (pleft->val < pright->val)
{
pHead = pleft;
pleft = pleft->next;
}
else
{
pHead = pright;
pright = pright->next;
}
ListNode* temp = pHead;
while (pleft != nullptr && pright != nullptr)
{
if (pleft->val < pright->val)
{
temp->next = pleft;
pleft = pleft->next;
temp = temp->next;
}
else
{
temp->next = pright;
pright = pright->next;
temp = temp->next;
}
}
if (pleft == nullptr)
temp->next = pright;
if (pright == nullptr)
temp->next = pleft;
return pHead;
}
ListNode* Mergesort(ListNode* pHead)
{
if (pHead == nullptr || pHead->next == nullptr)
return pHead;
//split list 对半分割 快慢指针 得到的slow为中间点
ListNode* fast = pHead;
ListNode* slow = pHead;
while (fast->next != nullptr && fast->next->next != nullptr)
{
fast = fast->next->next;
slow = slow->next;
}
ListNode* Left = pHead;
ListNode* Right = slow->next;
slow->next = nullptr;
ListNode* pLeft = Mergesort(Left);
ListNode* pRight = Mergesort(Right);
return MergeTwo(pLeft, pRight);
}