C语言使用链表时，有些时候会对链表中的数据进行排序。下边介绍使用链表时可用的排序方法，冒泡排序和选择排序。

<>冒泡排序
NODE* bubblesort(NODE* Head) { NODE *pfirst=NULL,*psecond=NULL,*pend=NULL;
pend 很有意思 while(pfirst->next != pend)//内循环 { if(pfirst->date > pfirst->next->
date) { temp=pfirst->date; pfirst->date=pfirst->next->date; pfirst->next->date=
temp; } pfirst=pfirst->next; } pend=pfirst;//减少最后的已排好的循环 pfirst=Head; } return
<>选择排序
/*链表的选择排序*/ NODE* selectsort(NODE* head) { NODE *pfirst=NULL,*psecond=NULL,*
while(pfirst->next != pend)//内循环 { if(psecond->date > pfirst->next->date) { temp
=psecond->date; psecond->date=pfirst->next->date; pfirst->next->date=temp; }
pfirst=pfirst->next; } psecond=psecond->next; pfirst=psecond; } return head; }
<>测试代码
/* *链表排序 Writen by YU */ #include<stdio.h> #include<stdlib.h> /*结果输出查看*/ void
endscan() { printf("\n点击回车继续..."); fflush(stdin); getchar(); } /*结构体*/ struct
node{ int date; struct node *next; }; typedef struct node NODE; //把struct node

pEnd; printf("输入数据，当输入0时停止\n"); pNew=(NODE*)malloc(sizeof(NODE)); scanf("%d",&
pNew->date); while(pNew->date != 0) { count++; if(count == 1) //如果为头节点 { pNew->
next= NULL; pEnd = pNew; pHead = pNew; } else //如果不是头结点 { pNew->next=NULL; pEnd
->next=pNew; pEnd=pNew; } pNew=(NODE*)malloc(sizeof(NODE)); scanf("%d",&pNew->
date); } free(pNew); return pHead; } /*输出链表*/ void print(NODE* Head) { NODE* p=
Head; while(p!=NULL) { printf("%d ",p->date); p=p->next; } } /*链表的冒泡排序*/ NODE*
; psecond=Head; int temp; while(pfirst != pend) //外循环 { //pfirst != pend 很有意思
while(pfirst->next != pend)//内循环 { if(pfirst->date > pfirst->next->date) { temp=
pfirst->date; pfirst->date=pfirst->next->date; pfirst->next->date=temp; } pfirst
/*链表的选择排序*/ NODE* selectsort(NODE* head) { NODE *pfirst=NULL,*psecond=NULL,*pend
pfirst->next != pend)//内循环 { if(psecond->date > pfirst->next->date) { temp=
psecond->date; psecond->date=pfirst->next->date; pfirst->next->date=temp; }
pfirst=pfirst->next; } psecond=psecond->next; pfirst=psecond; } return head; }
"\n排序后：\n"); print(pHead); endscan(); return 0; }

GitHub

Gitee