C 链表排序

        想把以前写的代码(CLrc类)用链表替换掉数组,在排序歌词中需要用到链表的排序,本来不想自己写的,奈何网上代码实在看不懂,于是便自己写了一个。这段代码没有实现链表的插入和删除函数,大家可以自己添加。源代码下载地址:(360云盘,360云盘可以在线查看源代码,有高亮)

// by sunnysab 2014.4.6
//
// sunnysab.blog.163.com
// blog.csdn.net/sunnysab
// 
// weibo.com/sunnysab
//
// 允许随便转载,建议保留原作者信息(非强制性)
//

#include <stdio.h>

// 结构声明
struct  list
{
    int  num;  // 要排序的数
    struct list *next;

}*head;

// 交换(*a)->num和(*b)->num
void  swap(struct list **a, struct list **b)
{
    int  t = 0;

    if(NULL != &a && NULL != &b)
    {
        t = (*a)->num;
        (*a)->num = (*b)->num;
        (*b)->num = t;
    }
}

// 在链表中找第num个节点
struct list *find(int num)
{
    struct list *t = head;
    int n = 0;

    if(NULL != t)
    {
        do
        {
            if(num != n)
            {
                n++;
                t = t->next;
                continue;
            }
            return t;
        }
        while(NULL != t);
    }
    return NULL;
}

// 统计链表内节点个数
int count()
{
    int n = 0;
    struct list  *t = head;

    if(NULL != head)
    {
        do
        {
            n++;
            t = t->next;
        }
        while(NULL != t);
    }
    return n;
}


// 排序
// 使用冒泡排序的思想
void sort()
{
    int i = 0, j = 0;
    int n = count();

    if(n != 0)
    {
        for(; i < n; i++)
        {
            for(j = 0; j < n - i; j++)
            {
                struct list  *a = find(j), 
                             *b = find(j + 1);

                if(NULL != a && NULL != b)
                {
                    if(a->num > b->num)
                    {
                        swap(&a, &b);
                    }
                }
            }
        }
    }

}

int main()
{
    struct list *t = NULL;

    // 自己制造一个链表
    // 大家可以自己完成add函数实现添加节点
    head = (struct list *)malloc(sizeof(struct list));
    head->num = 3;

    t = head;
    t->next = (struct list *)malloc(sizeof(struct list));
    t = t->next;
    t->num = 2;

    t->next = (struct list *)malloc(sizeof(struct list));
    t = t->next;
    t->num = 1;

    t->next = NULL;  // 链表尾
    t = head;

    sort(); // 排序

    // 以下代码输出
    do
    {
        printf("%d  ", t->num);
        t = t->next;
    }
    while(NULL != t);

    return 0;

}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值