想把以前写的代码(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;
}