题目要求
输入学生学号和成绩建立链表,以空格分隔,当输入学号为0时建立结束:
输入:
1 88
2 99
3 77
0 0
输出:
1 88.000000
2 99.000000
3 77.000000
#include <stdio.h>
#include <stdlib.h>
#define LEN sizeof(struct STUDENT)
struct STUDENT
{
long num;
float score;
struct STUDENT *next;
};
int n;
void print(struct STUDENT *head)
{
struct STUDENT *p;
p=head;//需要注意的地方就是这里不是head->next
//因为我们需要第一个数值,注意和前面模板的不同点
while(p!=NULL)
{
printf("%d %f\n",p->num,p->score);
p=p->next;
}
}
struct STUDENT *creat()
{
struct STUDENT *head,*p1,*p2; n=0;
p1=p2=( struct STUDENT*) malloc(LEN);
scanf("%ld%f",&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%f",&p1->num,&p1->score);
}
p2->next=NULL;
free(p1);
return(head);
}
void freenoheadlist(struct STUDENT *h)
{
struct STUDENT *t;
while(h)
{
t=h->next;
free(h);
h=t;
}
}
int main()
{
struct STUDENT *pt;
pt=creat();
print(pt);
freenoheadlist(pt);
return 0;
}
//之前因为眼瞎没看见,把print写成了,下面的形式
struct STUDENT *p;
p=head;
while(p->num!=0)
{
printf("%d %f\n",p->num,p->score);
p=p->next;
}
//返回值错误,虽然打印的是正确的