C语言使用链表时,有些时候会对链表中的数据进行排序。下边介绍使用链表时可用的排序方法,冒泡排序和选择排序。
此链表排序仅对链表中的数据进行排序,如果想进行对整个结构体的排序,也就是利用数据顺序来调整节点中的信息,需要对节点进行交换,但与此方法不同,望读者周知。
测试排序代码请先参考下边完整的测试代码。
编程环境:Visual C++ 6.0.
冒泡排序
NODE* bubblesort(NODE* Head)
{
NODE *pfirst=NULL,*psecond=NULL,*pend=NULL;
pfirst=Head;
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=pfirst->next;
}
pend=pfirst;//减少最后的已排好的循环
pfirst=Head;
}
return Head;
}
选择排序
/*链表的选择排序*/
NODE* selectsort(NODE* head)
{
NODE *pfirst=NULL,*psecond=NULL,*pend=NULL;
pfirst=head;
psecond=head;
int temp;
while(pfirst != pend) //外循环
{
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 定义为 NODE
int count = 0;
/*创建链表并输入数据*/
NODE* creat()
{
NODE *pHead=NULL,*pNew,*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* bubblesort(NODE* Head)
{
NODE *pfirst=NULL,*psecond=NULL,*pend=NULL;
pfirst=Head;
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=pfirst->next;
}
pend=pfirst;//减少最后的已排好的循环
pfirst=Head;
}
return Head;
}
/*链表的选择排序*/
NODE* selectsort(NODE* head)
{
NODE *pfirst=NULL,*psecond=NULL,*pend=NULL;
pfirst=head;
psecond=head;
int temp;
while(pfirst != pend) //外循环
{
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;
}
int main()
{
NODE* pHead=NULL;
pHead=creat();
printf("排序前:\n");
print(pHead);
// pHead=bubblesort(pHead); //冒泡排序
pHead=selectsort(pHead); //选择排序
printf("\n排序后:\n");
print(pHead);
endscan();
return 0;
}