#include<stdio.h>
#include<malloc.h>
#include<string.h>
struct student{
int num;
float score;
struct student *next;
};
int i = 0;
int main(){
struct student *creat(void);
struct student *merge(struct student *,struct student *);
void print(struct student *);
struct student *head1,*head2,*head;
printf("请输入链表A的数据,中间用空格隔开:\n");
head1 = creat();
printf("建立的链表A为:\n");
print(head1);
printf("请输入链表B的数据,中间用空格隔开:\n");
head2 = creat();
printf("建立的链表B为:\n");
print(head2);
head = merge(head1,head2);
printf("合并结果为:\n");
print(head);
return 0;
}
struct student *merge(struct student *head1,struct student *head2){
struct student *p1;
int i = 1,k = 0,tnum;
float tscore;
p1 = head1;
while(p1->next != NULL)
p1 = p1->next;
p1->next = head2;
p1 = head1;
while(i){
while(p1->next != NULL){
if(p1->num > p1->next->num){
tnum = p1->num;
p1->num = p1->next->num;
p1->next->num = tnum;
tscore = p1->score;
p1->score = p1->next->score;
p1->next->score = tscore;
k++;
}
p1 = p1->next;
}
p1 = head1;
if(k)
k = 0;
else
i = 0;
}
return head1;
}
void print(struct student *head){
struct student *pf;
pf = head;
if(head != NULL){
do{
printf("%-4d%-5.2f\n",pf->num,pf->score);
pf = pf->next;
}while(pf != NULL);
}
}
struct student *creat(){
struct student *p1,*p2,*head;
p1 = p2 = (struct student*)malloc(sizeof(struct student));
scanf("%d %f",&p1->num,&p1->score);
head = NULL;
while(p1->num != 0){
i++;
if(i == 1)
head = p1;
else
p2->next = p1;
p2 = p1;
p1 = (struct student*)malloc(sizeof(struct student));
scanf("%d %f",&p1->num,&p1->score);
}
p2->next = NULL;
i = 0;
return head;
}
合并两个链表,并按照顺序排序,谭浩强书中错误代码纠正
最新推荐文章于 2022-11-07 14:27:38 发布