合并两个链表,并按照顺序排序,谭浩强书中错误代码纠正

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值