免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1363 | 回复: 0
打印 上一主题 下一主题

单向链表的排序(冒泡法) [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-10-21 08:32 |只看该作者 |倒序浏览

单向链表的排序(冒泡法)
2008-01-08 16:54
struct note   /*结构体定义并声明变量head*/
{
int total;
struct note * next;
};
struct note * sort(struct note * note head) /*排序函数*/
{
int i;
struct note *p1,*stu,*p2,*p0=NULL;
printf("\nSorting...");
if(!head || !head->next)    /*没有结点或只有一个结点,直接退出。*/
return head;
if(!head->next->next) /*有两个结点,交换两个结点后退出。*/
{
if(head->totalnext->total)
{
stu=head;
head=head->next;
head->next=stu;
stu->next=NULL;
}
return head;
}
while(p0!=head->next->next) /*三个以上结点排序,使用冒泡排序法*/
{
p1=head;stu=p1->next;p2=stu->next;
while(p2!=p0)
{
if(stu->totaltotal)
{
struct note * p;
p1->next=p2;
stu->next=p2->next;
p2->next=stu;
p=stu;stu=p2;p2=p;
}
p1=p1->next;stu=stu->next;p2=p2->next;
}
p0=stu;
}
if(head->totalnext->total)/*特殊考虑前两个结点*/
{
stu=head;
head=head->next;
stu->next=head->next;
head->next=stu;
}
return head;
}
说明:p1,stu,p2是交换两个结点时使用的临时变量,p0指示内层循环的终止位置,初始值为NULL,内层循环一 次向前移动一个结点.直到p0指到第三个结点时为止.
每次判断,若stu的total成员小于p2的total成员,就使stu和p2交换.然后将p1,stu,p2顺次 后移,直到p2遇到p0为止.

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u3/103469/showart_2074435.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP