C語言鏈表中如何實現(xiàn)對一組數(shù)據(jù)進(jìn)行排序?
#include<stdio.h>
#include<stdlib.h>
#define NULL 0
struct student * creat();
struct student * link(struct student * head_a,struct student * head_b);
void print(struct student * head);
struct student{
int num;
float score[2];
struct student *next;
}stu;
int main(void)
{
struct student *head_a;
struct student *head_b,*head_c;
printf("請輸入a鏈表學(xué)生的數(shù)據(jù):0 0 0結(jié)束輸入\n");
head_a=creat();
print(head_a);
printf("請輸入b鏈表學(xué)生的數(shù)據(jù):0 0 0結(jié)束輸入\n");
head_b=creat();
print(head_b);
head_c=link(head_a,head_b);
printf("打印經(jīng)過排序之后的學(xué)生數(shù)據(jù),a,b鏈數(shù)據(jù)的結(jié)合\n");
print(head_c);
return 0;
}
struct student * creat()
{
int n=0;
struct student * head,*p1,*p2;
p1=p2=(struct student *)malloc(sizeof(struct student ));
scanf("%d%f%f",&p1->num,&p1->score[0],&p1->score[1]);
head=NULL;
while(p1->num!=0)
{
n=n+1;
if(n==1) head=p1;
else p2->next=p1;
p2=p1;
p1=(struct student *)malloc(sizeof(struct student));
scanf("%d%f%f",&p1->num,&p1->score[0],&p1->score[1]);
}
p2->next=NULL;
return head;
}
void print(struct student * head)
{
struct student *p;
p=head;
while(p!=NULL)
{
printf("%-10d%-10.1f%-10.1f\n",p->num,p->score[0],p->score[1]);
p=p->next;
}
return ;
}
struct student * link(struct student * head_a,struct student * head_b)
{
int n,m;
m=n=0;
struct student * head,*p1,*p2,*p3,*q;//q是在冒泡排序是(共需N-1趟排序)每趟的最后一次指針p1的位置,開始時q為Null
p1=head_a;
p2=head_b;
head=head_a;
while(p1->next!=NULL)
{p1=p1->next;n++;}
p1->next=p2;
p1=head_a;
while(p1!=NULL)
{
p1=p1->next;
n++; //n是計算鏈表的節(jié)點數(shù),以備后面的排序用
}
q=NULL;
p1=head_a;
p2=p1->next ;
while(m<n)
{
m++;
//以下是采用冒泡法進(jìn)行排序
while(p2!=q)
{
if(p1->num>p2->num)
{
if(head==p1) head=p2;
else p3->next=p2;
p1->next=p2->next;p2->next=p1;
//以下是按照 p3 p1 p2排序
p3=p2;p2=p1->next;
}
else
{
p3=p1;p1=p1->next;p2=p2->next;
}
}
q=p1;p1=head;p2=p1->next;
}
return (head);
}