效率不是很高,还需要优化
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
void quicksort(struct ListNode *pstart, struct ListNode *pend);
struct ListNode * partition(struct ListNode *pstart, struct ListNode **pend);
struct ListNode* sortList(struct ListNode* head){
//----------快速排序-----------------
if(head == NULL || head->next == NULL)
{
return head;
}
//增加一个头部哑结点,避免头部插入特殊情况的处理
struct ListNode *newhead = (struct ListNode *)malloc(sizeof(struct ListNode));
if(newhead == NULL)
{
exit(1);
}
newhead->val = 0;
newhead->next = head;
struct ListNode *pstart = newhead;
struct ListNode *pend = pstart;
while(pend->next != NULL) //让pend指向尾节点
{
pend = pend->next;
}
quicksort(newhead, pend); //快速排序
return newhead->next;
}
void quicksort(struct ListNode *pstart, struct ListNode *pend)
{
if(pstart->next != pend)
{
//mid指向分割节点的前一个节点
struct ListNode *mid = partition(pstart, &pend); //partition使用二级指针&pend,值传递需要修改pend值
if(mid == NULL)
{
return ;
}
printf("%d-%d-%d\n",pstart->val, mid->next->val, pend->val);
quicksort(pstart, mid);
quicksort(mid->next, pend);
}
return ;
}
struct ListNode * partition(struct ListNode *pstart, struct ListNode **pend)
{
//if(pstart->next == *pend)
//{
// return NULL;
//}
if(pstart == *pend || pstart->next == *pend) // 递归结束条件
{
printf("hahhaa\n");
return NULL;
}
struct ListNode *p = pstart;
struct ListNode *tmp = NULL;
struct ListNode *cmp = *pend; //cmp用于存放每次递归的分割节点,其他节点与它进行比较,确定插入位置
while(p->next != cmp)
{
if(p->next->val > cmp->val)
{
tmp = p->next;
p->next = p->next->next;
tmp->next = (*pend)->next;
(*pend)->next = tmp;
*pend = (*pend)->next;
}
else
{
p = p->next; //只有在无需移动节点的情况下(不许进行插入移动操作),循环指针才需要移动!!!!!
}
}
return p;
}