这个能运行,并能得到正确结果(TC3)
你那个排序应该有问题!自己处理吧!
程序代码:
#include<stdio.h>
#include<malloc.h>
#define LEN sizeof(struct student)
struct student
{long num;
float score;
struct student *next;
};
float x;
int n,sum=0;/*为全局变量*/
void main()
{
scanf("%f",&x); /*这一句是专为可以输入浮点数而加的,随便输入一个数即可,否则在运行时可能出现:scanf : floating point formats not linked 的错误*/
struct student *creat(void);/*函数声明建立链表*/
struct student *HB(struct student *,struct student *);/*函数声明合并两个链表*/
void print(struct student *);/*函数声明输出合并后的链表*/
struct student *ahead ,*bhead,*abh;
printf("请输入链表A:\n");
ahead=creat();/*调用函数输入链表A*/
sum=sum+n;
printf("请输入链表B:\n");
bhead=creat();/*调用函数输入链表B*/
sum=sum+n;
abh=HB(ahead,bhead);/*调用函数将两链表合并*/
print(abh);/*调用函数输出合并后的链表*/
}
struct student *creat(void)/*定义函数建立链表,此函数带回一个指向表头的指针*/
{
struct student *head=NULL;
struct student *p1,*p2;
n=0;
p1=p2=(struct student *)malloc(LEN);/*开辟一个新单元,注意此时p1和p2指向的位址相同*/
printf("input number&score of student :\n");
printf("if number is 0 ,stop inputing ,\n");
scanf("%ld,%f",&p1->num,&p1->score);
printf("%ld,%f\n",p1->num,p1->score);
while(p1->num !=0)
{
n=n+1;
if(n==1)
head=p1;/*使head指向新开辟的结点*/
else
p2->next=p1;/*把新结点的地址赋给第一个结点的next成员*/
p2=p1;/*使p2指向刚才建立的结点*/
p1=(struct student *)malloc(LEN);/*开辟另一个结点*/
scanf("%ld,%f",&p1->num,&p1->score);
printf("%ld,%f\n",p1->num,p1->score);
}
p2->next=NULL;/*链表建立结束*/
return head;
}
/*一下是算法核心*/
struct student *HB(struct student *ah,struct student *bh)/*函数定义合并两个链表*/
{
struct student *pa1,*pa2,*pb1,*pb2;
long po;/*中间值*/
pa1=pa2=ah;
pb1=pb2=bh;
while(pa2->next!=NULL)
pa2=pa2->next;/*使pa2指向另一个结点*/
pa2->next=pb2;/*把链表B的起始位址接到链表A后*/
/*接下来是实现排序*/ /*这个排序应该是有问题的先注释掉*/
/*
while(pa1->next!=NULL)
{
if(pa1->num>pb1->num)
{
po=pa1->num;
pa1->num=pb1->num;
pb1->num=po;
}
pa1=pa1->next;
pb1=pb1->next;
}
*/
return ah;
}
void print(struct student *head)/*输出函数*/
{
struct student *p;
p=head;
printf("\n There are %d records: \n",sum);
printf("输出合并后的链表\n");
while(p!=NULL)
{
printf("%ld,%f\n",p->num,p->score);
p=p->next;/*指向下一个结点*/
}
}