单链表的快速排序

#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值