将两个升序排列的链表合并后升序排序打印.

来源:互联网 发布:国外游戏源码交易平台 编辑:程序博客网 时间:2024/06/09 13:45

说的再多,我不如放码过来,大家看不懂哪里,可以评论,尴尬忘了注释了。。。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define LEN sizeof(struct Student)
struct Student
{
long num; 
float score;
struct Student *next;
};


int n;  //全局变量n、用记录链表的结点数. 


struct Student *creat(void);   //创建链表的函数原型声明. 


void print(struct Student *head);   //输出链表的函数原型声明. 


struct Student *merge(struct Student *La,struct Student *Lb);  //对两个带有头结点链表的函数声明. 


int main()
{
printf("Tip : The two LinkLists should be ascending order !\n\n");
struct Student *p1,*p2,*p;
printf("Create A. ");
p1=creat();
print(p1);
printf("Create B. ");
p2=creat();
print(p2);
p=merge(p1,p2);
printf("\nTip: Linklist A and B sorted.\n");
print(p);

return 0;
}


struct Student *creat(void)
{
struct Student *head;
struct Student *p1,*p2;
n=0;
head=(struct Student *)malloc(LEN);   
p1=p2=(struct Student *)malloc(LEN); 
head->next=NULL; 
printf("Please input num and score of students : \n");
scanf("%ld%f",&p1->num,&p1->score);
while(p1->num!=0)    //当输入的X.num!=0 的时候链入链表. 

n=n+1;                        //结点数增加. 
if(n==1) head->next=p1;     
else p2->next=p1;
p2=p1;
p1=(struct Student *)malloc(LEN);
scanf("%ld%f",&p1->num,&p1->score);
}
p2->next=NULL;    
free(p1);
return(head);
}


void print(struct Student *head)
{
struct Student *p;
p=head->next;
printf("Now,These %d records are :\n",n);
if(head->next!=NULL)
{
do
{
printf("%-12ld%-12.2f\n",p->num,p->score);
p=p->next;
}while(p!=NULL);
}
}


struct Student *merge(struct Student *La,struct Student *Lb)   //该代码是根据学生的学号来排序的. 
{
struct Student *a,*b,*c;
c=La;               //让定义的结构体指针C指向A链表.然后再A表的原有基础之上链入B表的结点. 
a=La->next;
b=Lb->next;
while(a!=NULL && b!=NULL)
{
if(a->num <= b->num)
{
c->next=a;   
c=a;
a=a->next;
n++;
}
else
{
c->next=b;
c=b;
b=b->next;
n++;
}
}
if(a!=NULL) c->next=a;
else c->next=b;

free(Lb);
return La;
}

1 0
原创粉丝点击