//第九章章末习题第10题
#include//建立a b两链表包含学号成绩,把两个链表合并升序排列输出。求思路!
#include
#define LEN sizeof(struct student)
struct student
{
long num;
int score;
struct student * next;
};
struct student lista,listb;
int n,sum=0;
int main()
{
struct student * creat(void);//创建链表函数
struct student * insert(struct student ,struct student *);//合并排序函数
void print(struct student *);//输出函数
struct student * ahead, * bhead, abh;
printf("input list a:\n");
ahead = creat();
sum = sum + n;//此语句不理解,请兄台解释下
printf("input list b:\n");
bhead = creat();
sum = sum + n;//此语句不理解
abh = insert(ahead,bhead);
print(abh);
return 0;
}
struct student creat(void)
{
struct student * p1, p2,* head;
n = 0;
p1 = p2 = (struct student * )malloc(LEN);
printf("input number && score of student:\n");
printf("if number is 0,please stop inputing:\n");
scanf("%ld,%d",&p1->num,&p1->score);
head=NULL;
while(p1->num != 0)
{
n = n+1;
if(n == 1)
head = p1;
else
p2->next = p1;
p2=p1;
p1 = (struct student *)malloc(LEN);
scanf("%ld,%d",&p1->num,&p1->score);
}
p2->next = NULL;
return (head);
}
//建立insert函数用来合并两个链表
struct student * insert(struct student * ah,struct student * bh)//问题就是
//这个功能函数直接不理解
{
struct student * pa1,* pa2,* pb1,* pb2;
pa2 = pa1 = ah;//此处不理解
pb2 = pb1 = bh;//此处不理解
do
{while((pb1->num > pa1->num) && (pa1->next != NULL))
{
pa2 = pa1;
pa1 = pa1->next;
}//此处不理解
if(pb1->num <= pa1->num)
{
if(ah == pa1)
ah = pb1;
else
pa2->next = pb1;
pb1 = pb1->next;
pb2->next = pa1;
pa2 = pb2;
pb2 = pb1;
}//此处不理解
}
while((pa1->next != NULL)||(pa1 == NULL) && (pb1 != NULL));
if((pb1 != NULL) && (pb1->num > pa1->num) && (pa1->next == NULL))
pa1->next = pb1;//此处不理解
return (ah);
}
//输出函数
void print(struct student * head)
{
struct student * p;
printf("There are %d records:\n",sum);
p = head;
if(p != NULL)
do
{
printf("%ld,%d\n",p->num,p->score);
p = p->next;
}
while(p != NULL);
}
我建议楼主看看老谭的《C程序设计》第三版,里面对链表的各项操作讲的很清晰的,下面是前三版中将链表插入的操作,希望对楼主有帮助。
struct student *insert(struct student *head, struct student *stud)
{ struct student *p0,*p1,*p2;
p1=head;
p0=stud;
if(head==NULL) {head=p0; p0->next=NULL;}
else{while((p0->num>p1->num) && (p1->next!=NULL))
{p2=p1; p1=p1->next;}
if(p0->num<=p1->num)
{ if(head==p1) head=p0;
else p2->next=p0; p0->next=p1;}
else {p1->next=p0; p0->next=NULL;}}
n=n+1;
return(head);
}