该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
书面作业_14:
1. 建立一个如下图所示的静态链表,它由3个结点组成,每个结点中的数据部分包括学生的学号,姓名和三门课程的成绩。要求先建立链表,再输出各结点中的数据,结构体的成员名称如右下角所示,类型的定义位于main()函数之前,其它代码写在main( )中。
链表的输出结果:
#include
#include
struct Student
{int num;
char name[20];
float score[4];
struct Student * next;
};
int main(){
struct Student a,b,c,* head,* p;
a.num=10101;strcpy(a.name,"张?丹獭?);a.score[0]=89;a.score[1]=95;a.score[3]=91;
b.num=10103;strcpy(b.name,"彭í浩?");b.score[0]=99;b.score[1]=89;b.score[3]=90;
c.num=10105;strcpy(c.name,"张?磊え?);c.score[0]=85;c.score[1]=95;c.score[3]=97;
head=&a;
a.next=&b;
b.next=&c;
c.next=NULL;
p=head;
do{
printf("%ld %s %5.lf %5.lf %5.lf\n",p->num,p->name,p->score[0],p->score[1],p->score[3]);
p=p->next;
}while(p!=NULL);
return 0;
}
2. 建立一个如上图所示的动态链表,结构体的成员、类型定义位置、各结点的内容与上一题相同,不同之处是:
(1)定义creat()函数,实现创建动态链表功能(学号为0时结束输入);
(2)定义print()函数,实现输出链表各结点功能;
(3)上述两函数的定义位于main()函数的后面;
程序运行结果如下所示:
#include
#include
#define LEN sizeof(struct Student)
struct Student{
int num;
char name[20];
float score[4];
struct Student * next;
};
int n;
struct Student * creat(){
struct Student * head;
struct Student * p1,* p2;
n=0;
p1=p2=(struct Student *)malloc(LEN);
scanf("%ld %s %f %f %f",&p1->num,&p1->name,&p1->score[0],&p1->score[1],&p1->score[3]);
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 %s %f %f %f",&p1->num,&p1->name,&p1->score[0],&p1->score[1],&p1->score[3]);
}
p2->next=NULL;
return (head);
}
void print(struct Student * head){
struct Student * p;
printf("\nNow,Three%drecords are:\n",n);
p=head;
if(head!=NULL)
do{
printf("%d %s %lf %lf %lf\n",p->num,p->name,p->score[0],p->score[1],p->score[3]);
p=p->next;
}while(p!=NULL);
}
int main(){
struct Student * head;
head=creat();
print(head);
return 0;
}