#include<iostream>
#include<ctime>
using namespace std;
//单链表节点
struct SList
{
int data;
struct SList* next;
};
void bulid_slist(SList** phead, int n) //指向指针的指针
{
int i;
SList* ptr = *phead;
for(i = 0; i < n; ++i)
{
SList* temp = new SList;
temp->data = rand() % n; //产生n个n以内的随机数
temp->next = NULL;
if(ptr == NULL)
{
*phead = temp;
ptr = temp;
}
else
{
ptr->next = temp;
ptr = ptr->next;
}
}
}
void print_slist(SList* phead) //输出链表
{
SList *ptr = phead;
while(ptr)
{
printf("%d ", ptr->data);
ptr = ptr->next;
}
printf("\n");
}
void my_swap(int *a,int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
void sort_slist(SList* phead, SList* pend) //将头指针为phead,尾指针为pend的链表进行排序
{
if(phead == NULL)
return ;
if(phead == pend)
return ;
SList *pslow = phead;
SList *pfast = phead->next;
SList *ptemp = phead;
while(pfast != pend)
{
if(pfast->data < phead->data) //每次都选择待排序链表的头结点作为划分的基准
{
pslow = pslow->next;
my_swap(&pslow->data , &pfast->data); //pslow指针指向比基准小的结点组成的链表
}
pfast = pfast->next;
}
my_swap(&pslow->data , &phead->data); //此时pslow指针指向比基准小的结点组成的链表的最后一个结点,也就是基准的位置,所以要与基准(head结点)交换
sort_slist(phead , pslow);
sort_slist(pslow->next ,pend); //右部分是比基准大的结点组成的链表
}
void destroy_slist(SList* phead)
{
SList* ptr = phead;
while(ptr)
{
SList* temp = ptr;
ptr = ptr->next;
delete temp;
}
}
int main(void)
{
srand(time(NULL));
printf("Before sort single list\n");
SList* phead = NULL;
bulid_slist(&phead, 100);
print_slist(phead);
printf("After sort single list\n");
sort_slist(phead, NULL);
print_slist(phead);
destroy_slist(phead);
system("pause");
return 0;
}
单链表的快速排序
最新推荐文章于 2024-04-11 21:39:22 发布