问题描述
- 新手上路,链表学习中,问题是对功能函数不理解,问题已备注,请帮我在问题处写思路,尤其功能函数,谢谢!
- //第九章章末习题第10题
#include//建立a b两链表包含学号成绩,把两个链表合并升序排列输出。求思路!
#include
#define LEN sizeof(struct student)struct student
{
long num;
int score;struct student * next;
};
struct student listalistb;
int nsum=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(aheadbhead);
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 0please 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 * ahstruct 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%dn""p->nump->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);
}